JMock / Mockito 使用方式
生活随笔
收集整理的這篇文章主要介紹了
JMock / Mockito 使用方式
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JMock使用總結(jié)
不修改開(kāi)發(fā)代碼,程序運(yùn)行時(shí)注入類(lèi)bugdao,返回mock對(duì)象給它
?
不需要注入spring /*@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml", "classpath:spring-druid.xml" })*/public class Test1 {
@Tested //mock的bugservice //@Autowired 同樣spring的注解也不需要 private BugServiceI bugService;@Injectable //注入到bugservice //@Autowired private BugDaoI bugDao;?
@Testpublic void test1() { final Tbug bug=new Tbug();bug.setName("sss");bug.setId("1");;final Map<String, Object> params = new HashMap<String, Object>();params.put("id", "1");new NonStrictExpectations() { // Expectations中包含的內(nèi)部類(lèi)區(qū)塊中,體現(xiàn)的是一個(gè)錄制被測(cè)類(lèi)的邏輯。 { bugDao.get("from Tbug t join fetch t.tbugtype bugType where t.id = :id", params);result = bug; // mock掉返回值 bugService.get("1");result = bug; } }; Bug b = bugService.get("1");System.out.println(b.getName()); //sss}?}
?
Mockito使用總結(jié)
不修改開(kāi)發(fā)代碼,程序運(yùn)行時(shí)注入類(lèi)bugdao,返回mock對(duì)象給它
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml", "classpath:spring-druid.xml" }) public class Test2 {@Autowiredprivate BugServiceI bugService;@Autowiredprivate BugDaoI bugDao;@Testpublic void test() {bugDao = mock(BugDaoI.class); Tbug bug=new Tbug();bug.setName("sss");bug.setId("1");;Map<String, Object> params = new HashMap<String, Object>();params.put("id", "1");doReturn(bug).when(bugDao).get("from Tbug t join fetch t.tbugtype bugType where t.id = :id", params); //mockbugService=new BugServiceImpl();ReflectionTestUtils.setField(bugService, "bugDao", bugDao); //注bugDao Bug b = bugService.get("1");System.out.println(b.getName());
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/season-xie/p/6741302.html
總結(jié)
以上是生活随笔為你收集整理的JMock / Mockito 使用方式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java程序发送邮件
- 下一篇: STM32 CJSON解析说明