JUnit测试不是Spring控制器中的触发方法

时间:2015-03-09 07:30:59

标签: java spring testing junit

我想在JUnit的帮助下测试我的控制器。我是新来的。我已经为此编写了一些代码,但它没有出现在我的函数listCard中。我的控制器是:

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

我编写了以下代码进行测试:

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?"));
    }
}

1 个答案:

答案 0 :(得分:1)

首先 - 从控制器中删除@Configuration注释。它不属于这里。

第二次 - 在测试时考虑使用Mockito,因为您在控制器中注入了服务。您更新的测试类应该类似于下面的

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

如果您需要进一步的信息/帮助,请在评论中说明。