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

时间:2017-10-17 12:33:04

标签: java spring unit-testing mockito

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

@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

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

编辑=当我添加 .contextPath("/postdb"))时它会起作用..不确定这是否正确,但是当我编写另一个测试并且不包含任何请求参数时,该测试会给出200而不是400或404 .. ..

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

以下对我来说没问题

公共类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());
    }

}

答案 2 :(得分:0)

尝试添加查询参数,如下所示:

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