JMock使用總結spring
不修改開發代碼,程序運行時注入類bugdao,返回mock對象給它fetch
不須要注入spring
/*@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml", "classpath:spring-druid.xml" })*/
public class Test1 {ui
@Tested //mock的bugservice //@Autowired 一樣spring的註解也不須要 private BugServiceI bugService; @Injectable //注入到bugservice //@Autowired private BugDaoI bugDao;
@Test public 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中包含的內部類區塊中,體現的是一個錄製被測類的邏輯。 { 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 }
}spa
Mockito使用總結hibernate
不修改開發代碼,程序運行時注入類bugdao,返回mock對象給它code
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-hibernate.xml", "classpath:spring-druid.xml" }) public class Test2 { @Autowired private BugServiceI bugService; @Autowired private BugDaoI bugDao; @Test public 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); //mock bugService=new BugServiceImpl(); ReflectionTestUtils.setField(bugService, "bugDao", bugDao); //注bugDao
Bug b = bugService.get("1"); System.out.println(b.getName());}