Skip to content
Advertisement

How to write JUnit 5 test cases for the following code?

This is the method to write the JUnit test cases for

public List<LoanApiCallEntity> getAllApiCallDetails() {

    return apiCallDetailsRepository.findAll();
}

Inside the LoanApiCallEntity class these are the following:

public class LoanApiCallEntity {

    @Id
    @Column(name = "loan_api_call_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int apiCallId;
    
    @CreationTimestamp
    @Column(name="call_timestamp", nullable=false, updatable=false)
    private Timestamp callDateTime;
    
    @Column(name = "request_url")
    private String requestURL;
    
    @Column(name="request_parameters")
    private String requestParameters;
    
    @Column(name = "username")
    private String username;
    
    @Column(name = "response_status")
    private String responseStatus;

}

This is the test case I have tried, but it shows an error:

@MockBean ApiCallDetailsServiceImpl apiCallDetailsService;

@Test public void apiCallDetailsServiceImpltest() {

 LoanApiCallEntity entity = new LoanApiCallEntity();

    entity.setApiCallId(1);

    Mockito.doReturn(entity).when(this.apiCallDetailsService).getAllApiCallDetails();

    Assertions.assertEquals(entity.getApiCallId(),1);

}

The error shown while running the project (mvn test) is – LoanApiCallEntity cannot be returned by getAllApiCallDetails().

Advertisement

Answer

getAllApiCallDetails() returns a list of objects so you need to provide a list as a mock value in the doReturn function call.

Advertisement