mockito5.4.0单元测试(13) --捕获mock对象调用某方法时的参数ArgumentCaptor,断言其参数值
mockito官方文档地址:https://www.javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html#captors
先准备两个dto类:
@Slf4j
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResearchDto implements Serializable {
private static final long serialVersionUID = -8610563322176923066L;
private Long id;
private String username;
private Research2Dto research2Dto;
}
@Slf4j
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Research2Dto implements Serializable {
private static final long serialVersionUID = -8610563322176923066L;
private Long id;
private String username;
}
case 1:
@Test
public void test_ArgumentCaptor_case1() {
// mock一个对象
List singleMock = mock(List.class);
// 调用一次add,放入"zhangsan"
singleMock.add("zhangsan");
// 如果这一行代码去掉注释被执行的话,那么执行到这一行:verify(singleMock).add(argument.capture())会报错:Wanted 1 time: xxx, But was 2 times: xxx.
// 意思是应该只调用一次add方法,但实际上调用了两次add方法。
//singleMock.add("lisi");
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
// 验证mock对象调用add方法时的参数类型
verify(singleMock).add(argument.capture());
// 断言mock对象调用add方法时的参数等于"zhangsan",而非其他值
assertEquals("zhangsan", argument.getValue());
}
case 2:
@Test
public void test_ArgumentCaptor_case2() {
// mock一个对象
ResearchDto dtoMock = mock(ResearchDto.class);
dtoMock.setUsername("myname123");
Research2Dto research2Dto = new Research2Dto();
research2Dto.setUsername("research2Dto_username");
dtoMock.setResearch2Dto(research2Dto);
// ArgumentCaptor<ResearchDto> argument = ArgumentCaptor.forClass(dtoMock.getClass());
ArgumentCaptor<Research2Dto> argument = ArgumentCaptor.forClass(Research2Dto.class);
// 捕获mock对象调用setResearch2Dto方法时的参数类型,即argument.capture()应该是Research2Dto对象
verify(dtoMock).setResearch2Dto(argument.capture());
// 断言mock对象调用调用setResearch2Dto方法时的参数,即research2Dto对象的username等于值"research2Dto_username",而非其他值
assertEquals("research2Dto_username", argument.getValue().getUsername());
}
end.