我正在编写 Junit 测试用例,我想模拟 KafkaTemplate 方法kafkaTemplate.send(TOPIC_NAME, "someData");
。在我的项目中,我使用的是 Spring Boot 和 Kafka。
下面是StudentRecords
课堂。我mockito
用于模拟依赖项。
@Component
public class StudentRecords {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Value("${topicNameForStudents}")
private String TOPIC_NAME;
public String sendStudentData(StudentDTO studentDTO) {
String studentStr = null;
try {
if(null == studentDTO) {
throw new StudentException("studentDTO Object cant be null");
}
if(studentDTO.getId() == null) {
throw new StudentException("Id cant be empty");
}
ObjectMapper mapper = new ObjectMapper();
studentStr = mapper.writeValueAsString(srvgExecution);
kafkaTemplate.send(TOPIC_NAME, studentStr);
return "SUCCESS";
} catch (JsonProcessingException e) {
e.printStackTrace();
return "ERROR";
}
}
}
测试类如下:
@ExtendWith({ SpringExtension.class, MockitoExtension.class })
class StudentRecordsTest {
@InjectMocks
StudentRecords studentRec;
@Mock
private KafkaTemplate<String, String> kafkaTemplate;
@Test
void testSendStudentData() {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setId(1);
studentDTO.setName("ABC");
studentDTO.setAddress("Some Address");
Mockito.when(kafkaTemplate.send(Mockito.anyString(), Mockito.anyString()));
studentRec.sendStudentData(studentDTO);
}
}
我收到以下错误
[ERROR] Errors:
[ERROR] studentRec.testSendStudentData: » UnfinishedStubbing
它正在线上发生studentRec.sendStudentData(studentDTO);
我如何为此解决/编写junit?
@Test
void testSendStudentData() {
StudentDTO studentDTO = new StudentDTO();
studentDTO.setId(1);
studentDTO.setName("ABC");
studentDTO.setAddress("Some Address");
Mockito.when(kafkaTemplate.send(Mockito.anyString(), Mockito.anyString()));
studentRec.sendStudentData(studentDTO);
Mockito.verify(kafkaTemplate).send(Mockito.anyString(), Mockito.anyString());
}
将junit更新到以上一个后,在此语句中出现以下错误Mockito.verify(kafkaTemplate).send(Mockito.anyString(), Mockito.anyString());
Argument(s) are different! Wanted:
kafkaTemplate.send(
<any string>,
<any string>
);