2.7 灵活的参数匹配

在record和verify阶段进行方法匹配时,

  • 对于原始类型对象,数值相同即可;
  • 对于Object的子类,需要equals()返回true;
  • 对于数组,需要长度相等且每个对象equals()返回true;

除此之外,如果不关心replay时的具体参数,可以使用anyXyz或者withXyz(...)方法。

使用"any"

@Test
public void someTestMethod(@Mocked final DependencyAbc abc)
{
   final DataItem item = new DataItem(...);

   new Expectations() {{
      abc.voidMethod(anyString, (List<?>) any);
   }};

   new UnitUnderTest().doSomething(item);

   new Verifications() {{
      abc.anotherVoidMethod(anyLong);
   }};
}
  • 任何的基本类型都有对应的anyXyzanyString对应任意字符串。
  • any对应任意的对象,在使用时需要进行显式类型转换: (CastClass) any
  • mockit.Invocations类中有可以使用所有anyXyz
  • 使用时参数位置需要一致

使用"with"

any的限制太宽松,with可以选择特定的子集。

@Test
public void someTestMethod(@Mocked final DependencyAbc abc) {
   final DataItem item = new DataItem(...);

   new Expectations() {{
      abc.voidMethod("str", (List<?>) withNotNull());
      abc.stringReturningMethod(withSameInstance(item), withSubstring("xyz"));
   }};

   new UnitUnderTest().doSomething(item);

   new Verifications() {{
      abc.anotherVoidMethod(withAny(1L));
   }};
}

也可以自定义with方法。

使用"null"

null可以与任何对象匹配,好处是避免类型转换,但是需要有一个any或者with

@Test
public void TestMethod(@Mocked final Dependency mock) {
    new StrictExpectations() {{
    
        //测试会失败,因为没有any或者with
        mock.mockMethod(2,  null);
        
        //测试通过
        mock.mockMethod(anyInt,  null);
    }};
    mock.mockMethod(new Integer(2), "hello world");
}

如何需要的是null,则应该用 withNull() 方法。

varargs

要么使用常规的参数,要么使用any/with,不能混合使用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容