Java spring启动单元测试断言错误
在一个基于SpringBoot的Rest项目中,我有一个这样的控制器 它调用服务,服务层调用dao层。现在我正在为控制器编写单元测试代码。当我运行此命令时,错误显示 java.lang.AssertionError:应为:但为: 我不知道我哪里做错了:Java spring启动单元测试断言错误,java,spring-boot,Java,Spring Boot,在一个基于SpringBoot的Rest项目中,我有一个这样的控制器 它调用服务,服务层调用dao层。现在我正在为控制器编写单元测试代码。当我运行此命令时,错误显示 java.lang.AssertionError:应为:但为: 我不知道我哪里做错了: public class CustomerController { private static final Logger LOGGER = LogManager.getLogger(CustomerController.
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;
}
}
客户控制器的测试
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
(也可能是@products
)注释来标记,该注释指定它期望从客户端获得什么类型的媒体,以及它返回给客户端的媒体类型
由于我看到您的测试代码使用MediaType.APPLICATION\u JSON\u UTF8
运行生产代码,您可能应该将端点标记为消费和生产应用程序\u JSON\u 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);
}
}
你的测试没有太多测试。您应该模拟UserService
,而不是您的控制器。除此之外,您正在尝试将JSON字符串转换为JSON字符串。所以我不知道你为什么要这么做。创建一个Customer
并将其转换为JSON或按原样发布JSON。
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());