abhishekgarg
abhishekgarg

Reputation: 164

JUnit test is not triggering method in Spring controller

I want to test my controller with the help of JUnit. I am new to this. I have written some code for this but it is not coming to my function listCard. My controller is:

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/v1/card")
@Configuration
public class CardManagementController {
    private final static Logger LOG = LoggerFactory
            .getLogger(CardManagementController.class);

    @Autowired
    ICardService cardService;

    @RequestMapping(value = "", produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.GET)
    public @ResponseBody GetCardResponse getCard(
            @ModelAttribute @Valid GetCardRequest request, BindingResult results)
            throws RuntimeException, ValidationException {
        if (results.hasErrors()) {
            LOG.error("error occured occur while fetching card response");
            throw new ValidationException(
                    "Error Occoured while validiating card request");
        }
        GetCardResponse response = null;
        response = cardService.getCard(request);
        return response;
    }

    @RequestMapping(value = "", produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.POST)
    public @ResponseBody AddCardResponse addCard(
            @ModelAttribute AddCardRequest request, BindingResult results)
            throws RuntimeException, ValidationException {
        if (results.hasErrors()) {
            LOG.error("error occured while adding the card");
            throw new ValidationException(
                    "Error Occoured while validiating addcard request");
        }
        LOG.debug("add Card with POST method");
        AddCardResponse response = null;
        response = cardService.addCard(request);
        return response;
    }

    @RequestMapping(value = "", produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.DELETE)
    public @ResponseBody DeleteCardResponse deleteCard(
            @ModelAttribute @Valid DeleteCardRequest request,
            BindingResult results) throws RuntimeException, ValidationException {
        if (results.hasErrors()) {
            LOG.debug("error occured while delting the card");
            throw new ValidationException(
                    "Error Occoured while validiating delete card request");
        }
        DeleteCardResponse response = null;
        response = cardService.deleteCard(request);
        return response;
    }

    @RequestMapping(value = RestURIConstants.LISTCARD, produces = RestURIConstants.APPLICATION_JSON, method = RequestMethod.GET)
    public @ResponseBody ListCardResponse listCard(
            @ModelAttribute @Valid ListCardRequest request) throws RuntimeException, ValidationException {

        ListCardResponse response = null;
        response = cardService.listCards(request);
        return response;
    }

    @ExceptionHandler({ ValidationException.class})
    @ResponseBody
    public CPPException handleValidationException(ValidationException ex) {
        LOG.error("Exception occoured",ex);
        CPPException exception = new CPPException(ex.getMessage());
        exception.setStatus(500);
        return exception;
    }

    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public CPPException handleException(RuntimeException ex) {
        LOG.error("Exception occoured", ex);
        CPPException exception = new CPPException("Internal Server Error");
        exception.setStatus(500);
        return exception;
    }
}

and I have written the following code for testing:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.my.cpp.controller.CardManagementController;
import com.my.cpp.request.ListCardRequest;
import com.my.cpp.service.impl.CardServiceImpl;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/spring/application-context.xml"})
public class CardApiTest {

    private MockMvc mockMvc;

    //@Autowired
    private CardManagementController cm=new CardManagementController();
    @Autowired
    private CardServiceImpl cmr;

    @Before
    public void setUp() throws Exception {
    mockMvc= MockMvcBuilders.standaloneSetup(cm).build();        
    }
    @Test
    public void testList() throws Exception{
        final ListCardRequest lr=new ListCardRequest();
        this.mockMvc.perform(get("/v1/card/list?"));
    }
}

Upvotes: 0

Views: 1057

Answers (1)

Ammar
Ammar

Reputation: 4024

First - Remove the @Configuration annotation from your controller. It doesn't belong here.

Second - Consider using Mockito while testing, since you have a service injected in your controller. Your updated test class should look something similar as below

@RunWith(MockitoJUnitRunner.class)
public class CardApiTest {

    private MockMvc mockMvc;

    @InjectMocks
    private CardManagementController cm;

    @Mock
    private ICardService cardService;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.standaloneSetup(cm).build();

        // Instantiate cardListRequest and cardListResponse here
        when(cardService.listCards(cardListRequest)).thenReturn(cardListResponse);
    }

    @Test
    public void testList() throws Exception{
        this.mockMvc.perform(get("/v1/card/list?"));
    }
}

Let know in comments if you need further info / assistance.

Upvotes: 1

Related Questions