Подтвердить что ты не робот

Junit Test для контроллера Spring MVC 4 для проверки параметров @PathVariable в @RequestMapping

У меня есть следующий код контроллера, для которого я должен написать тестовый пример JUnit.

public class EquipmentController {

    private Map<String, Equipment> equiList = new HashMap <String,Equipment>();

    @RequestMapping("/rest/equipment/{Number}")
    public Equipment getEquipment(@PathVariable String Number){

        if(!equiList.containsKey(Number)){
            lNumber = DEFAULT;
        }
        return equiList.get(Number);

    }
}

Я пишу тестовый пример JUnit для того же, что и ниже:

import static org.springframework.test.web.ModelAndViewAssert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({/* include live config here
    e.g. "file:web/WEB-INF/application-context.xml",
    "file:web/WEB-INF/dispatcher-servlet.xml" */})
public class EquipmentControllerTest {

    @Inject
    private ApplicationContext applicationContext;

    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    private HandlerAdapter handlerAdapter;
    private EquipmentController controller;

    @Before
    public void setUp() {
       request = new MockHttpServletRequest();
       response = new MockHttpServletResponse();
       handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
       // Get the controller from the context here
       controller = new EquipmentController();
    }

    @Test
    public void testgetEquipment() throws Exception {
       request.getUriString()("lNumber");
       final Equipment equip = handlerAdapter.handle(request, response, 
           controller);
       assertViewName(equip, "view");
    }
}

Но я не уверен, что этот тестовый класс верен или нет, поскольку я новичок в JUnit.

Кто-нибудь может предложить, как это сделать.

4b9b3361

Ответ 1

Создайте макет вашего контроллера и используйте MockMvc, чтобы проверить свои методы:

import static org.springframework.test.web.ModelAndViewAssert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({/* include live config here
    e.g. "file:web/WEB-INF/application-context.xml",
    "file:web/WEB-INF/dispatcher-servlet.xml" */})
public class EquipmentControllerTest {

    private MockMvc mockMvc;

    private EquipmentController controller;

    @Before
    public void setUp() {

       this.mockMvc = MockMvcBuilders.standaloneSetup(equipmentController).build()
    }

    @Test
    public void testgetEquipment() throws Exception {
      this.mockMvc.perform(get("/rest/equipment/{Number}", 3))
           .andExpect(status().isOk())
    }
}

где "3" представляет значение вашей переменной пути.