![](/img/trans.png)
[英]Getting HTTP response code 200 in API response even after returning ResponseEntity with HttpStatus.BAD_REQUEST
[英]Issue with responseEntity . MockMvc.Perform() gives 200 status code even if the ResponseEntity.HttpStatus is 201
我正在尝试模拟控制器的post方法。 我希望它返回状态码201(CREATED)。 但是它的状态代码为200。下面是代码,这是我的控制器类
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
public @RestController
class SomeController{
@PostMapping("/insertString")
public ResponseEntity<String> insertString(String str) {
return new ResponseEntity<>(new String("monster"),HttpStatus.CREATED);
}
}
这是我的junit测试服
package com.example.demo;
import static org.junit.Assert.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.mockito.Mockito.anyString;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.RequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
public class TestClass {
@Autowired
private MockMvc mockMvc;
@MockBean
private SomeController someController;
@Test
public void test() throws Exception {
ResponseEntity<String> entity = new ResponseEntity<>(HttpStatus.CREATED);
when(someController.insertString(anyString())).thenReturn(entity);
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/insertString")
.accept(MediaType.APPLICATION_JSON)
.content("monkey")
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder)
.andExpect(status().isCreated())
.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
}
errorim得到的是
java.lang.AssertionErrror:状态应该为:<201>,但为:<200>
虽然我在RequestEntity对象中提到了状态为HttpStatus.CREATED,但为什么我会得到200。请问有人可以帮忙吗
尝试改变
public ResponseEntity<String> insertString(String str)
至
public ResponseEntity<String> insertString(@RequestBody String str)
我已经使用上述代码运行了测试,测试通过了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.