簡體   English   中英

Mockito 中的動態 thenReturn() 語句

[英]Dynamic thenReturn()-Statements in Mockito

id喜歡有一個方法可以動態創建某個class的Mock對象。

static Scanner mockScanner(int personsEntering, int personsLeaving) {
        Scanner scanner = mock(Scanner.class);

        when(scanner.readyToProcessPerson()).thenReturn(true);

        when(scanner.personWantsToEnter()).thenReturn(true).thenReturn(true).thenReturn(false);
        return scanner;
}

Scanner 中的 personWantsToEnter() 方法根據一個人想要進入或離開,返回 true 或 false。 我希望我的方法 mockScanner() 返回一個模擬對象,該對象根據參數“personsEntering”和“personsLeaving”模擬人的進出。 (例如:當 'personsEntering' 為 2 且 'personsLeaving' 為 1 時,模擬對象的行為應如上面的代碼示例中所示。)有什么可能的方法嗎?

您可以在for()循環中動態調用thenReturn() ,具體取決於給定的 arguments personsEnteringpersonsLeaving 每次您必須更新從when()方法獲得的OngoingStubbing<Boolean>變量時。 您的代碼可能如下所示:

public static Foobar mockFoobar(int personsEntering, int personsLeaving) {
    Foobar f = Mockito.mock(Foobar.class);
    
    OngoingStubbing<Boolean> stub = Mockito.when(f.personWantsToEnter());
    
    for (int i=0; i<personsEntering; i++) {
        stub = stub.thenReturn(true);
    }
    for (int i=0; i<personsLeaving; i++) {
        stub = stub.thenReturn(false);
    }
    return f;
}

(我用Foobar替換了Scanner以避免與java.util.Scanner混淆)

請參閱以下單元測試,它將基於給定的mockFoobar()調用通過:

@Test
void test() throws Exception {
    Foobar test = mockFoobar(4, 2);
    Assertions.assertTrue(test.personWantsToEnter());
    Assertions.assertTrue(test.personWantsToEnter());
    Assertions.assertTrue(test.personWantsToEnter());
    Assertions.assertTrue(test.personWantsToEnter());
    Assertions.assertFalse(test.personWantsToEnter());
    Assertions.assertFalse(test.personWantsToEnter());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM