简体   繁体   中英

Complex JUnit test Case

I am writing a test case using JUnit for a method that takes an ENUM in the switch statement. This is the method to be tested.

public <T extends BaseServiceResponse> T postProcess(T response,
        ClientResponse clientResponse) throws EISClientException {  

    List<Message> messages = response.getMessages();
    if(messages==null || messages.size()==0) {
        return response;
    }

    Map<String, Message> messagesMap = populateMessages(response.getMessages());
    ConditionOperator condition = getCondition();

    switch(condition) {
        case OR:
            checkORCondition( messagesMap );
            break;
        case AND:
            checkANDCondition( messagesMap );
            break;
    }       
    return response;
}   

What I've done so far is:

@Test
public void testPostProcess() throws Exception {
    clientResponse = mock(ClientResponse.class);

    RetrieveBillingServiceResponse response = new RetrieveBillingServiceResponse();
    BillingOverview billingOverView = new BillingOverview();

    Message message = new Message();
    message.setMessageCode("200");
    message.setMessageType(MessageTypeEnum.MESSAGE_TYPE_INFO);
    message.setMessageText("Service completed successfully");

    response.setEntity(billingOverView);
    response.setMessages(Arrays.asList(message));

    MessageToExceptionPostProcessFilter postProcessFilter = new MessageToExceptionPostProcessFilter();
    RetrieveBillingServiceResponse serviceResponse = postProcessFilter.postProcess(response, clientResponse);

    assertEquals("200", serviceResponse.getMessages().get(0).getMessageCode());

I am getting a NullPointerException for conditonOperator which is of type ENUM and this holds only two members OR and AND which are the cases in the switch statement. Can someone help me out how should I proceed with this test.

Thanks

Enum variables can be null. The getCondition() method is returning null. Why it's returning null, we can't really guess without seeing code you haven't shown us.

If getCondition() is private method you cannot mock it. If it is public method, you can mock it or if you have a setCondition, you can directly set the ENUM.

Assuming if you are using Mockito or PowerMock or EasyMock you can use something like

when(postProcessFilter.getCondition()).thenReturn(Enum.OR);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM