zoukankan      html  css  js  c++  java
  • JMock / Mockito 使用方式

    JMock使用总结

    不修改开发代码,程序运行时注入类bugdao,返回mock对象给它

    不需要注入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;
    @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
        }

     }

    Mockito使用总结

    不修改开发代码,程序运行时注入类bugdao,返回mock对象给它

    @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());
    }
  • 相关阅读:
    TCP/IP三次握手四次挥手
    注解(JDK1.5之后)
    枚举(JDK1.5之后)
    局部内部类
    非静态内部类
    静态内部类
    匿名内部类
    接口
    根父类:java.lang.Object
    native关键字
  • 原文地址:https://www.cnblogs.com/season-xie/p/6741302.html
Copyright © 2011-2022 走看看