Reputation: 51
I have the following class:
public class Foo {
public Foo() {
initField1();
initField2();
initField3();
}
}
I need to change the behaviour (to mock) initField1()
and initField3()
for them making do nothing or something else that they actually do. I am interested in executing the actual code of initField2().
I want to write the following test:
Foo foo = new Foo();
assertTrue(foo.myGet());
myGet()
returns an attribute of Foo that has been computed by initField2()
.
The initField()
methods are of course private.
How can I do such a thing?
Thanks for your help and best regards.
Upvotes: 5
Views: 3201
Reputation: 11775
Considering anything can happen in legacy code :) you can use PowerMock
to supress methods as described in http://code.google.com/p/powermock/wiki/SuppressUnwantedBehavior
import static org.powermock.api.support.membermodification.MemberMatcher.methods;
import static org.powermock.api.support.membermodification.MemberModifier.suppress;
@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class FooTest {
@Test
public void testSuppressMethod() throws Exception {
suppress(methods(Foo.class, "initField1", "initField3"));
Foo foo = new Foo();
}
}
Still, you should re-factor the class after you've got adequate test coverage for it.
Upvotes: 5
Reputation: 4649
I think there is something wrong in what you want to do.
As far as I understand, a mocking framework such as Mockito or PowerMock is meant to mock interaction between the object under test and its dependencies.
As I understand your question, you want to mock part of the object behavior, and test the rest of it.
In your case, you want to test something that will never happen, as initField2()
will never be called without calls to initField1()
and initField3()
If the reason you don't want to call initField1()
and initField3
is because these methods interact with other objects, or filesystem or DB, then you should rather inject the dependencies via constructor argument or annotated setters, and just inject mocks for your tests. And to instantiate your object with its dependencies properly set up, use the factory pattern, the builder pattern, or even better, use a dependency injection framework such as the one from Spring or Google Guice.
If the reason you d'ont want to call initField1()
and initField3
is because they deal with different business logic in your object, then this smells (as in http://martinfowler.com/books/refactoring.html) like you're breaking the single responsibility principle, and you should refactor.
Upvotes: -1