gpt4 book ai didi

java - 用于 Spring MVC 4 Controller 的 Junit 测试用例检查 @RequestMapping 中的 @PathVariable 参数

转载 作者:IT老高 更新时间:2023-10-28 13:56:32 26 4
gpt4 key购买 nike

我有以下 Controller 代码,我必须为其编写 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 的新手。

任何人都可以建议如何做到这一点。

最佳答案

创建一个你的 Controller 的模拟并使用 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”代表路径变量的值。

关于java - 用于 Spring MVC 4 Controller 的 Junit 测试用例检查 @RequestMapping 中的 @PathVariable 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31937870/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com