为了账号安全,请及时绑定邮箱和手机立即绑定

是否可以将 Mockito 中的某些返回值列入黑名单?

是否可以将 Mockito 中的某些返回值列入黑名单?

郎朗坤 2021-09-15 16:18:11
背景我正在尝试使用 Mockito 在类中测试此方法:该方法的第一种情况是字符串等于常量。该方法的第二种情况是字符串等于除常量之外的任何其他内容。这是这个问题的字符串版本,关于除某个整数之外的任何内容。public class Class {    private SomeOtherObjectWithAMethod someOtherObjectWithAMethod;    public Class(SomeOtherObjectWithAMethod someOtherObjectWithAMethod){        this.someOtherObjectWithAMethod = someOtherObjectWithAMethod;    }    public void method(){        if(helperObject.obtainAString().equals(HelperObject.A_STRING_CONSTANT)){            someOtherObjectWithAMethod.thisMethod("stringarg");        }        else{            someOtherObjectWithAMethod.thisMethod("differentarg");        }    }我知道在 Mockito 你可以根据durron597更改 mockito 中的某些返回值(但只有最后一个有效)null在thenReturn()方法中输入作为不返回任何内容的方式。使用anyString()作为一个虚拟字符串。返回一个布尔值。部分解决方案我已经对第一个案例进行了单元测试,(str.equals("This string"))如下所示:private Class instantiatedClass;@Testpublic void testMethod_thisString(){    whenever(helperObject.obtainAString()).thenReturn(HelperObject.A_STRING_CONSTANT);    instantiatedClass.method()    verify(someOtherObjectWithAMethod).thisMethod("stringarg");}我将编写另一个类似的测试用例方法。我在下面注释掉了我需要帮助的部分:@Testpublic void testMethod_notThisString(){    whenever(helperObject.obtainAString()).thenReturn(/* A String that is not HelperObject.A_STRING_CONSTANT */);    instantiatedClass.method()    verify(someOtherObjectWithAMethod).thisMethod("differentarg");}题如何测试除特定值(或多个值)之外的任何字符串?
查看完整描述

3 回答

?
至尊宝的传说

TA贡献1789条经验 获得超10个赞

creating random strings如果它们不等于特定值(值),您可以查找并使用它们。


查看完整回答
反对 回复 2021-09-15
?
拉莫斯之舞

TA贡献1820条经验 获得超10个赞

您可以Mockito.doAnswer( answer )更好地控制创建的String


所以像:


List<String> blacklist = Arrays.asList("aaaa","bbbb");

Mockito.doAnswer((i)-> { 

    String x=RandomStringUtils.random(4);

    while(blacklist.contains(x)){

        x=RandomStringUtils.random(4);

    }

    return x;

}).when(helperObject).obtainAsString();


查看完整回答
反对 回复 2021-09-15
?
回首忆惘然

TA贡献1847条经验 获得超11个赞

虽然我不知道如何做“除某些字符串外的任何字符串”,但这解决了我的问题:


@Test

public void testMethod_notThisString(){

    whenever(helperObject.obtainAString()).thenReturn(HelperObject.CONSTANT1, HelperObject.CONSTANT2, HelperObject.CONSTANT3);

    instantiatedClass.method()

    verify(someOtherObjectWithAMethod).thisMethod("differentarg");

}

这遵循Overriding Stubbing的逻辑。


查看完整回答
反对 回复 2021-09-15
  • 3 回答
  • 0 关注
  • 155 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信