spring + junit + mockito : automatically mock @Autowired
the idea came from this post: http://java.dzone.com/tips/automatically-inject-mocks
the only problem i've found with this setup is that i need to manually reset mock objects between tests because mocks are created only once.
but then i found out the @DirtiesContext annotation which forces the destruction and recreation of the Spring context after each test, so new mocks are created each time.
the only problem i've found with this setup is that i need to manually reset mock objects between tests because mocks are created only once.
but then i found out the @DirtiesContext annotation which forces the destruction and recreation of the Spring context after each test, so new mocks are created each time.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContextTest.xml")
public class MainControllerTest {
@Autowired
MainController mainController ;
MyService myService ;
@Before
public void setupTest() {
myService = (MyService)ReflectionTestUtils.getField(mainController,"myService") ;
}
@Test
@DirtiesContext
public void testMock1() throws Exception {
when(myService.getTestString()).thenReturn("MOCK!") ;
Assert.assertEquals("MOCK!",mainController.getString()) ;
verify(myService).doSomething("MOCK!");
}
@Test
@DirtiesContext
public void testMock2() throws Exception {
when(myService.getTestString()).thenReturn("MOCK!") ;
verify(myService,never()).doSomething("MOCK!");
}
}

0 Commenti:
Posta un commento
Iscriviti a Commenti sul post [Atom]
<< Home page