Question

I want to use pattern 1 suggested in the following link: https://code.google.com/p/mockito/wiki/MockingObjectCreation and have the following class:

public class MyClass {
  private AnyType anyObject;
  private Foo foo; // Foo is a thirdparty class

  public MyClass(AnyType anyObject) {
    //...
    foo = makeFoo();
  }

  private Foo makeFoo() {
    return new Foo();
  }
}

I'm trying to make a test as follows:

@Test
public void myTestMethod() {
  MyClass myClass = Mockito.spy(new MyClass());

  // now i want to do something like this:
  Foo mockFoo= Mockito.mock(Foo.class);
  // Mockito.doReturn(mockFoo).when(myClass).makeFoo());
}

The problem is my factory method makeFoo is a private method, so I can't access it. I don't want to make it public just for the test. My test classes are not in the same package as my productive code either, so making it visible only for the package won't work.

Update: Now i found another problem. Assumed that makeFoo() is public, 'mockFoo' will not be returned either, yet the real makeFoo() method is invoked. This happens since the invocation of makeFoo() (in the constructor of MyClass) is prior to the creation of mockFoo.

Does anyone know how to solve this problem or am I doing something totally wrongly?

Thanks you guys in advance for helping!!

Was it helpful?

Solution

Have a look at whenNew of PowerMockito. This allows to "overwrite" the constructor call of an object and return a mock of it instead.

http://powermock.googlecode.com/svn/docs/powermock-1.3.7/apidocs/org/powermock/api/mockito/PowerMockito.html#whenNew%28java.lang.Class%29

http://www.gitshah.com/2010/05/how-to-mock-constructors-using.html

OTHER TIPS

If you just need to set a field inside your class, it's doable with MockitoAnnotations

You just need to create fields you need, annotate them and in unit test before section call MockitoAnnotations.initMocks(this)

In your case it will look like:

 @Spy
 @InjectMocks
 MyClass myClass;
 @Mock
 Foo foo;

 @Before
 public void initMocks() {
     MockitoAnnotations.initMocks(this);
 }

Please read also documentation above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top