2 回答

TA貢獻(xiàn)1797條經(jīng)驗(yàn) 獲得超6個(gè)贊
你可以這樣做:
與@SuppressWarnings("未選中")
@Test
@SuppressWarnings("unchecked")
void TestDoSomething(){
SubClass sb = mock(SubClass.class);
Example ex = new Example(sb);
ArgumentCaptor<Map<String, CompoundClass>> argCaptor = ArgumentCaptor.forClass(Map.class);
ex.doSomeThing();
verify(sb).doSomeThingSubClass(argCaptor.capture());
System.out.println(argCaptor.getValue().get("x").a);
}
或使用 junit5 和 @Captor 注釋?zhuān)?/p>
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
@TestInstance(Lifecycle.PER_METHOD)
public class TestDoSomething {
@Captor
private ArgumentCaptor<Map<String, CompoundClass>> argCaptor;
@Test
void TestDoSomething2(){
SubClass sb = mock(SubClass.class);
Example ex = new Example(sb);
ex.doSomeThing();
verify(sb).doSomeThingSubClass(argCaptor.capture());
System.out.println(argCaptor.getValue().get("x").a);
}
}

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
可以使用 Mockito 的Captor注解來(lái)聲明ArgumentCaptor.
例如,以下測(cè)試編譯并輸出aa:
@Captor
private ArgumentCaptor<Map<String, CompoundClass>> argCaptor;
@Test
void TestDoSomehing(){
MockitoAnnotations.initMocks(this);
SubClass sb = mock(SubClass.class);
Example ex = new Example(sb);
ex.doSomeThing();
verify(sb).doSomeThingSubClass(argCaptor.capture());
System.out.println(argCaptor.getValue().get("x").a);
}
從Javadocs:
使用注釋的優(yōu)點(diǎn)之一@Captor是您可以避免與捕獲復(fù)雜泛型類(lèi)型相關(guān)的警告。
添加回答
舉報(bào)