亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否可以將 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 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號