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 { }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步