springMVC 整合mockito单元测试学习

来源:互联网 发布:java生成随机数的方法 编辑:程序博客网 时间:2024/05/18 20:10

之前一直在一个误区里。徘徊了一两天;因为看了好多mockito网站,都没找到关于mockito用法根本作用。都比较书面化。所以在这里希望能写的简单点对于初学者,而且对这方面经验弱的学者们!

首先,mockito是一般结合junit测试框架一起使用的。他们区别也很明显,mockito主要是用于模拟测试,mock模拟外部依赖,根据自己的期望,设置等操作实现,来判断代码逻辑,参数等是否正确,如果,测试编译不通过,说明不通过。这里不会跟数据库之类的打交道。比如存一个数据,编译通过数据库不会多出一条数据。所以这就是跟junit的区别。他只是模拟代码测试。Mock用来判断测试通过还是失败。

   Mockito是一套非常强大的测试框架,被广泛的应用于Java程序的unit test中,而在其中被使用频率最高的恐怕要数"Mockito.when(...).thenReturn(...)"了。那这个用起来非常便捷的"Mockito.when(...).thenReturn(...)",其背后的实现原理究竟为何呢?为了一探究竟,笔者实现了一个简单的MyMockito,也提供了类似的"MyMockito.when(...).thenReturn(...)"支持。当然这个实现只是一个简单的原型,完备性和健壮性上都肯定远远不及mockito(比如没有annotation支持和thread safe),但应该足以帮助大家理解"Mockito.when(...).thenReturn(...)"的核心实现原理。

点击打开链接

至于,关于mockito的介绍和原理,大家可以看官网,http://blog.csdn.net/bboyfeiyu/article/details/52127551点击打开链接

用法案例讲解网址,点击打开链接http://www.cnblogs.com/Ming8006/p/6297333.html

接下来,进行案例开发


pom.xml

<!-- test --><dependency>    <groupId>junit</groupId>    <artifactId>junit</artifactId>    <version>${junit.version}</version>    <scope>test</scope></dependency><!-- mockito --><dependency>    <groupId>org.mockito</groupId>    <artifactId>mockito-all</artifactId>    <version>${mockito.version}</version>    <scope>test</scope></dependency>

测试类:

@RunWith(SpringJUnit4ClassRunner.class)// 整合Spring-Test与JUnit//@ContextConfiguration(locations = {"classpath*:spring/spring-context.xml"})@ContextConfiguration(locations ="classpath*:/spring/spring-context.xml")// 加载需要的配置配置@Transactional          //事务回滚,便于重复测试 extpublic class EnterpriseInfoServiceTest extends BaseTest {    @Autowired    @InjectMocks//@InjectMocks用于标识被测对象,从而把由@mock表示的依赖对象自动注入到被测对象中    protected EnterpriseInfoService enterpriseInfoService;//测试的类(serviceImpl)    @Mock//@Mock用于表示依赖对象    private EnterpriseInfoMapper mapper;//依赖的类(dao)    @Before    public void setUp() {//可以在每一次单元测试前准备执行一些东西        MockitoAnnotations.initMocks(this);    }       @Test    public void deletes() {        String[] str = {"123","124","125"};       // enterpriseInfoService.deleteByKeys(str);        boolean falg = enterpriseInfoService.deleteByKeys(str);
        Assert.assertTrue(falg );//验证返回的结果是不是正确的
}
 @Test  
  public void update(){ 
       EnterpriseInfo enterpriseInfo = new EnterpriseInfo(); 
       enterpriseInfo.setEntNum("123");
        enterpriseInfo.setEntNameCn("中安");
        enterpriseInfo.setEntType("1"); 
       enterpriseInfo.setRecordFlag(2);
        enterpriseInfoService.update(enterpriseInfo);  
      verify(mapper, times(1)).update(enterpriseInfo);  //针对返回值为void方法的验证
      //或       
     //  doThrow(new RuntimeException()).when(mapper).update(enterpriseInfo);         }

这是关于mockito所有用法的demo点击打开链接http://pan.baidu.com/s/1o8SF9qE

原创粉丝点击