2 回答
TA贡献1797条经验 获得超6个赞
你可以这样做:
与@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 注释:
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贡献1865条经验 获得超7个赞
可以使用 Mockito 的Captor注解来声明ArgumentCaptor.
例如,以下测试编译并输出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:
使用注释的优点之一@Captor是您可以避免与捕获复杂泛型类型相关的警告。
添加回答
举报