11. verify验证方法调用
package lesson11; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class VerifyTest { @Mock private SimpleDao simpleDao; @Test public void testRealCallAdd() { SimpleService simpleService = new SimpleService(simpleDao); Simple simple = new Simple(); when(simpleDao.exist(simple)).thenReturn(false); when(simpleDao.add(simple)).thenReturn(true); when(simpleDao.update(simple)).thenReturn(true); boolean result = simpleService.merge(simple); assertThat(true, equalTo(result)); /** * 利用verify确定究竟调用的是哪个方法 */ verify(simpleDao, times(1)).add(simple); verify(simpleDao, times(0)).update(simple); } @Test public void testRealCallUpdate() { SimpleService simpleService = new SimpleService(simpleDao); Simple simple = new Simple(); when(simpleDao.exist(simple)).thenReturn(true); when(simpleDao.add(simple)).thenReturn(true); when(simpleDao.update(simple)).thenReturn(true); boolean result = simpleService.merge(simple); assertThat(true, equalTo(result)); verify(simpleDao, times(0)).add(simple); verify(simpleDao, times(1)).update(simple); } @Test public void testMerge() { SimpleService simpleService = new SimpleService(simpleDao); Simple simple = new Simple(); when(simpleDao.exist(simple)).thenReturn(true, false); when(simpleDao.add(simple)).thenReturn(true); when(simpleDao.update(simple)).thenReturn(true); boolean result = simpleService.merge(simple); assertThat(true, equalTo(result)); verify(simpleDao, times(0)).add(simple); verify(simpleDao, times(1)).update(simple); result = simpleService.merge(simple); assertThat(true, equalTo(result)); verify(simpleDao, times(1)).add(simple); verify(simpleDao, times(1)).update(simple); } @After public void destroy() { reset(simpleDao); } }
package lesson11; public class SimpleService { public SimpleDao simpleDao; public SimpleService(SimpleDao simpleDao) { this.simpleDao = simpleDao; } public boolean merge(Simple simple) { boolean exist = simpleDao.exist(simple); if (exist) { return simpleDao.update(simple); } else { return simpleDao.add(simple); } } }
package lesson11; public class SimpleDao { public boolean exist(Simple simple) { throw new RuntimeException(); } public boolean update(Simple simple) { throw new RuntimeException(); } public boolean add(Simple simple) { throw new RuntimeException(); } }
package lesson11; public class Simple { }