簡體   English   中英

Mockito ArgumentCaptor 是 null

[英]Mockito ArgumentCaptor is null

我是初學者,請多多包涵。 :)

場景:JUnit 在 IntelliJ / Maven 上使用 Mockito 進行測試。 我正在嘗試使用 Java 中的 ArgumentCaptor 讀取傳遞的參數。 問題是,這個俘虜本身就是 null。 俘虜似乎根本不起作用。

@Captor
    private ArgumentCaptor<Invoice> cap; 
    ...        
        verify(invoiceDao).insert(cap.capture());

我懷疑問題是,由於其他原因,我不能使用 @ExtendWith(MockitoExtension.class) 。 (我在 @BeforeEach 方法中放置了一些存根,它拋出了 UnnecessaryStubbingExceptions。)

有沒有辦法在沒有@ExtendWith 的情況下使用 th ArgumentCaptor? 或者這首先不是我問題的原因嗎?

如果我完全迷失在這里,我很抱歉。 提前感謝您的幫助!

實際上,@Captor 注釋僅在您啟用@Captor時才有效。

但是您也可以手動初始化 ArgumentCaptor 而不使用@Captor注釋:

ArgumentCaptor<Xxx> argumentCaptor = ArgumentCaptor.forClass(Xxx.class);

或者,如果您只需要避免 UnnecessaryStubbingExceptions,您可以在@ExtendWith(MockitoExtension.class)注釋上方添加@MockitoSettings(strictness = Strictness.LENIENT) Strictness.LENIENT),並繼續使用@Captor/@Mock。

@ExtendWith(MockitoExtension.class)不需要將@Captor與 JUnit4 一起使用。 這是一個 JUnit5 功能,我仍在使用 JUnit4。

對我來說,正如您所描述的那樣,使用@Capture注釋以及ArgumentCaptor.forClass(Invoice.class)失敗

Unfortunately the class I was trying to capture had methods that were final and it seems Mockito was just returning null... I needed to rework how I tested to avoid the class with the final.

暫無
暫無

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

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