2015-03-09 3 views
0

Я хочу проверить свой контроллер с помощью JUnit. Я новичок в этом. Я написал для этого код, но он не подходит к моей функции listCard. Мой контроллер:Тест JUnit не запускается в контроллере весны

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

Первый - Удалите @Configuration аннотацию из контроллера. Он здесь не принадлежит.

Second - Рассмотрите возможность использования 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?")); 
    } 
} 

Сообщите, если вам нужна дополнительная информация/помощь.

+0

спасибо за помощь, теперь ее работа отлично. – abhishekgarg

+0

Рад помочь! Примите ответ в пользу будущих читателей :) –

Смежные вопросы