Java: How do I mock a method of a field when that field isn't exposed?
java, junit, mockito, unit-testing
Solution
This is what you want:
@RunWith(MockitoJUnitRunner.class)
public class MyAppTest {
@Mock private OpportunitiesService mocked_m_oppsSvc;
@InjectMocks MyApp myApp;
@Test public void when_MyApp_uses_OpportunititesService_then_verify_something() {
// given
given( mocked_m_oppsSvc.whatever()).willReturn(...);
// when
myApp.isUsingTheOpportunitiesService(...);
// then
verify...
assertThat...
}
}
Using: Mockito 1.9.0, BDD style, FEST-Assert AssertJ.
Hope that helps :)
Problem
I'm using Java 6, JUnit 4.8.1, and writing a console application. My application has a member field that isn't exposed … ``` public class MyApp { ... private OpportunitiesService m_oppsSvc; private void initServices() { … m_oppsSvc = new OpportunitiesServiceImpl(…); } ... } ``` I want to mock a behavior such that whenever one method from my service is called, (e.g. `m_oppsSvc.getResults()`), the same result is always returned. How do I do that? There's no setter method for the field. I'm currently working with Mockito 1.8.4. Is it possible to do this with Mockito or some other mock framework?