0

I am writing Junit test case and I want to mock KafkaTemplate method kafkaTemplate.send(TOPIC_NAME, "someData");. In my project, I am using spring boot and Kafka.

Below is the StudentRecords class. I am using mockito for mocking the dependencies.

@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";
        }
    }
}

And test class is as follows:

@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);
        
    }

}

And I getting the following error

   [ERROR] Errors: 
   [ERROR]   studentRec.testSendStudentData: ยป UnfinishedStubbing

It is happening at line studentRec.sendStudentData(studentDTO);

How I can resolve/write the junit for this?


@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());
        
}

after updating the junit to above one, ended up with below error at this statement Mockito.verify(kafkaTemplate).send(Mockito.anyString(), Mockito.anyString());

Argument(s) are different! Wanted:
kafkaTemplate.send(
    <any string>,
    <any string>
);
halfer
  • 19,824
  • 17
  • 99
  • 186
user2587669
  • 532
  • 4
  • 10
  • 22

1 Answers1

0

Your mock statement is incomplete.

Mockito.when(kafkaTemplate.send(Mockito.anyString(), Mockito.anyString()));

KafkaTemplate's send method returns a ListenableFuture object and hence you need to have your mock return it.

I understand, you are not really using the returned value as part of your code.

In that case you may simply return null as below.

Mockito.when(kafkaTemplate.send(Mockito.anyString(), Mockito.anyString())).thenReturn(null);

Although, I would suggest you should ideally check for return value for better error handling, but that can be a different story altogether.

In case you do plan to handle error by checking the return value, your above mock statement can be written to return both success and fail cases.

You may check below thread for more details on how to set the correct mock expectations for KafkaTemplate.

How to mock result from KafkaTemplate

  • i have already tried this Mockito.when(kafkaTemplate.send(Mockito.anyString(), Mockito.anyString())).thenReturn(null); still error exists โ€“ user2587669 Jul 26 '20 at 06:57
  • @user2587669 Can you please paste entire error in that case. Is it UnfinishedStubbing error or do you get 'Argument(s) are different' error or both ? โ€“ Sandeep Lakdawala Jul 26 '20 at 07:07
  • @user2587669 one more point reg this member variable 'TOPIC_NAME'. Since you are not doing anything for this in your test class, I would assume it is being set to null. In that case it will not match up to your mock anyString() matcher. Try to set the value for TOPIC NAME using a setter maybe. โ€“ Sandeep Lakdawala Jul 26 '20 at 07:15