正在处理基于 Spring 启动的 Rest 项目,我有一个这样的控制器哪个调用服务,服务层调用道层。现在我正在为控制器编写单元测试代码。当我运行这个时,错误说
java.lang.AssertionError: 预期:<201>但 was:<415>
我不知道我哪里做错了:
public class CustomerController {
private static final Logger LOGGER = LogManager.getLogger(CustomerController.class);
@Autowired
private CustomerServices customerServices;
@Autowired
private Messages MESSAGES;
@Autowired
private LMSAuthenticationService authServices;
@RequestMapping(value = "/CreateCustomer", method = RequestMethod.POST)
public Status createCustomer(@RequestBody @Valid Customer customer, BindingResult bindingResult) {
LOGGER.info("createCustomer call is initiated");
if (bindingResult.hasErrors()) {
throw new BusinessException(bindingResult);
}
Status status = new Status();
try {
int rows = customerServices.create(customer);
if (rows > 0) {
status.setCode(ErrorCodeConstant.ERROR_CODE_SUCCESS);
status.setMessage(MESSAGES.CUSTOMER_CREATED_SUCCESSFULLY);
} else {
status.setCode(ErrorCodeConstant.ERROR_CODE_FAILED);
status.setMessage(MESSAGES.CUSTOMER_CREATION_FAILED);
}
} catch (Exception e) {
LOGGER.info("Cannot Create the Customer:", e);
status.setCode(ErrorCodeConstant.ERROR_CODE_FAILED);
status.setMessage(MESSAGES.CUSTOMER_CREATION_FAILED);
}
return status;
}
}
CustomerController
的测试 .
public class CustomerControllerTest extends ApplicationTest {
private static final Logger LOGGER = LogManager.getLogger(CustomerControllerTest.class);
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@MockBean
private CustomerController customerController;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
Status status = new Status(200,"customer created successfully","success");
String customer = "{"customerFullName":"trial8900","customerPhoneNumber": "trial8900", "customerEmailID": "trial8900@g.com","alternateNumber": "trial8900","city": "trial8900","address":"hsr"}";
@Test
public void testCreateCustomer() throws Exception {
String URL = "http://localhost:8080/lms/customer/CreateCustomer";
Mockito.when(customerController.createCustomer(Mockito.any(Customer.class),(BindingResult) Mockito.any(Object.class))).thenReturn(status);
// execute
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post(URL)
.contentType(MediaType.APPLICATION_JSON_UTF8)
.accept(MediaType.APPLICATION_JSON_UTF8)
.content(TestUtils.convertObjectToJsonBytes(customer))).andReturn();
LOGGER.info(TestUtils.convertObjectToJsonBytes(customer));
// verify
MockHttpServletResponse response = result.getResponse();
LOGGER.info(response);
int status = result.getResponse().getStatus();
LOGGER.info(status);
assertEquals(HttpStatus.CREATED.value(), status);
}
}
HTTP 状态 415 为"不支持的媒体类型"。 终结点应使用@Consumes
(也可能是@Produces
(注释进行标记,指定它期望从客户端获得的媒体类型以及返回到客户端的媒体类型。
由于我看到您的测试代码使用 MediaType.APPLICATION_JSON_UTF8
执行您的生产代码,您可能应该将您的端点标记为消耗和生产APPLICATION_JSON_UTF8。
然后,您还需要确保错误处理中没有发生任何严重错误,因为在捕获生产代码生成的异常并生成HTTP响应的过程中,错误处理代码可能会生成不同的东西,例如生成包含HTML格式错误消息的有效负载的错误状态响应, 它将具有"text/html"的内容类型,您的测试代码无法理解它,而您的测试代码需要 JSON 即可理解。
使用以下基本测试类进行设置,并将 json 转换为字符串,将字符串转换为 json
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
还要验证您的帖子呼叫是否已发生,请检查以下示例
Mockito.doNothing().when(customerServices).create(Mockito.any(Customer.class));
customerServices.create(customer);
Mockito.verify(customerServices, Mockito.times(1)).create(customer);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());