尽管url工作,但Spring控制器测试失败



我正在尝试测试一个基本控制器:

@Autowired
DAOInterface db;
@RequestMapping(value = "/postdb", method = RequestMethod.GET)
@ResponseBody
public String postdb(
@RequestParam(value = "id", required = true) String id
) {
db.addEntry(id);
return "Added " + id + ".";
}

这个url的工作原理是,当我访问它时,它会将它添加到数据库中,并将字符串输出作为响应。

我正在尝试为它创建一个简单的单元测试:

@Autowired
MockMvc mockMvc;
@MockBean
DAOInterface daoInterface;
@Test
public void shouldReturnA200() throws Exception {
mockMvc.perform(get("/postdb?id=3"))
.andExpect(status().isOk());
}

但我得到了以下

MockHttpServletRequest:

HTTP Method = GET
Request URI = /postdb
Parameters = {id=[3]}
Headers = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = {}
Content type = null
Body = 
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status 
Expected :200
Actual   :404

不确定为什么每当我尝试访问它时它都能工作,但在运行此测试时失败。我看不出有什么问题。可能是因为我没有使用任何头或正式的响应体/视图,而只是输出一个String?

EDIT=添加 .contextPath("/postdb"))时有效。。不确定这是否是正确的方式,但当我写另一个测试,并且不包括任何请求参数时,该测试给出的是200,而不是400或404…

@Autowired
DAOInterface db;
@RequestMapping(value = "/postdb", method = RequestMethod.GET)
public ResponseEntity<String> postdb(@RequestParam(required = true) String id) {
db.addEntry(id);
return new ResponseEntity<>("Added " + id + ".", HttpStatus.OK);
}

测试:

@Test
public void shouldReturnA200() throws Exception {
mockMvc.perform(get("/postdb?id=3")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}

下面对我来说很好

公共类FirstWebController{

@RequestMapping(value = "/postdb", method = RequestMethod.GET)
@ResponseBody
public String postdb(@RequestParam(value = "id", required = true) String id) {
System.out.println("idddddddddddd "+id);
return "Added " + id + ".";
}

}

测试等级为

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class FirstWebControllerTest {
@Configuration
static class FirstWebControllerTestConfiguration {
@Bean
public FirstWebController firstWebController() {
return new FirstWebController();
}
}
@Autowired
private FirstWebController firstWebController;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = standaloneSetup(firstWebController).build();
}
@Test
public void shouldReturnA200() throws Exception {
mockMvc.perform(get("/postdb?id=3")).andExpect(status().isOk());
}
}

尝试添加如下查询参数:

@Test
public void shouldReturnA200() throws Exception {
mockMvc.perform(get("/postdb).param("id", "3"))
.andExpect(status().isOk());
}

相关内容

  • 没有找到相关文章

最新更新