猿问

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

背景

我正在尝试使用 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;


@Test

public void testMethod_thisString(){

    whenever(helperObject.obtainAString()).thenReturn(HelperObject.A_STRING_CONSTANT);

    instantiatedClass.method()

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

}

我将编写另一个类似的测试用例方法。我在下面注释掉了我需要帮助的部分:


@Test

public void testMethod_notThisString(){

    whenever(helperObject.obtainAString()).thenReturn(/* A String that is not HelperObject.A_STRING_CONSTANT */);

    instantiatedClass.method()

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

}

如何测试除特定值(或多个值)之外的任何字符串?


郎朗坤
浏览 156回答 3
3回答

至尊宝的传说

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

拉莫斯之舞

您可以Mockito.doAnswer( answer )更好地控制创建的String所以像:List<String> blacklist = Arrays.asList("aaaa","bbbb");Mockito.doAnswer((i)-> {&nbsp;&nbsp; &nbsp; String x=RandomStringUtils.random(4);&nbsp; &nbsp; while(blacklist.contains(x)){&nbsp; &nbsp; &nbsp; &nbsp; x=RandomStringUtils.random(4);&nbsp; &nbsp; }&nbsp; &nbsp; return x;}).when(helperObject).obtainAsString();

回首忆惘然

虽然我不知道如何做“除某些字符串外的任何字符串”,但这解决了我的问题:@Testpublic void testMethod_notThisString(){&nbsp; &nbsp; whenever(helperObject.obtainAString()).thenReturn(HelperObject.CONSTANT1, HelperObject.CONSTANT2, HelperObject.CONSTANT3);&nbsp; &nbsp; instantiatedClass.method()&nbsp; &nbsp; verify(someOtherObjectWithAMethod).thisMethod("differentarg");}这遵循Overriding Stubbing的逻辑。
随时随地看视频慕课网APP

相关分类

Java
我要回答