• 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());
    }
  • 相关阅读:
    SSM:Spring整合SpringMVC框架
    SSM:搭建整合环境
    SpringMVC:常用注解
    SpringMVC的入门案例
    base64
    windows设置exe开机自启动
    Python-wmi模块
    Base64String转为图片并保存
    java给图片添加水印图片
    uni-app中封装axios请求
  • 原文地址:https://www.cnblogs.com/season-xie/p/6741302.html
Copyright © 2020-2023  润新知