Mockito: Inject real objects into private @Autowired fields

I’m using Mockito’s @Mock and @InjectMocks annotations to inject dependencies into private fields which are annotated with Spring’s @Autowired: @RunWith(MockitoJUnitRunner.class) public class DemoTest { @Mock private SomeService service; @InjectMocks private Demo demo; /* … */ } and public class Demo { @Autowired private SomeService service; /* … */ } Now I would like to also … Read more

Mockito verify order / sequence of method calls

Is there a way to verify if a methodOne is called before methodTwo in Mockito? public class ServiceClassA { public void methodOne(){} } public class ServiceClassB { public void methodTwo(){} } public class TestClass { public void method(){ ServiceClassA serviceA = new ServiceClassA(); ServiceClassB serviceB = new ServiceClassB(); serviceA.methodOne(); serviceB.methodTwo(); } } 5 Answers 5

How to tell a Mockito mock object to return something different the next time it is called?

So, I’m creating a mock object as a static variable on the class level like so… In one test, I want Foo.someMethod() to return a certain value, while in another test, I want it to return a different value. The problem I’m having is that it seems I need to rebuild the mocks to get … Read more

throw checked Exceptions from mocks with Mockito

I’m trying to have one of my mocked objects throw a checked Exception when a particular method is called. I’m trying the following. @Test(expectedExceptions = SomeException.class) public void throwCheckedException() { List<String> list = mock(List.class); when(list.get(0)).thenThrow(new SomeException()); String test = list.get(0); } public class SomeException extends Exception { } However, that produces the following error. org.testng.TestException: … Read more

Mockito – difference between doReturn() and when()

I am currently in the process of using Mockito to mock my service layer objects in a Spring MVC application in which I want to test my Controller methods. However, as I have been reading on the specifics of Mockito, I have found that the methods doReturn(…).when(…) is equivalent to when(…).thenReturn(…). So, my question is … Read more

Injecting Mockito mocks into a Spring bean

I would like to inject a Mockito mock object into a Spring (3+) bean for the purposes of unit testing with JUnit. My bean dependencies are currently injected by using the @Autowired annotation on private member fields. I have considered using ReflectionTestUtils.setField but the bean instance that I wish to inject is actually a proxy … Read more