【问题标题】:spring boot unit test assertion errorspring boot 单元测试断言错误
【发布时间】:2017-06-22 06:50:01
【问题描述】:

在基于 Spring Boot 的 Rest 项目上工作我有一个这样的控制器 其中调用服务,服务层调用dao层。现在我正在为控制器编写单元测试代码。当我运行这个错误说

java.lang.AssertionError: 预期: 但原为:

我不知道我哪里做错了:

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

    }

【问题讨论】:

  • 您的测试没有进行太多测试。您应该模拟 UserService 而不是您的控制器。除此之外,您正在尝试将 JSON 字符串转换为 JSON 字符串。所以不知道你为什么要这样做。创建 Customer 并将其转换为 JSON 或按原样发布 JSON。

标签: java spring-boot


【解决方案1】:

HTTP 状态 415 是“不支持的媒体类型”。您的端点应该标有@Consumes(也可能还有@Produces)注释,指定它期望客户端提供的媒体类型以及返回给客户端的媒体类型。

由于我看到您的测试代码使用MediaType.APPLICATION_JSON_UTF8 执行您的生产代码,您可能应该将您的端点标记为消费和生产 APPLICATION_JSON_UTF8。

那么您还需要确保在您的错误处理中没有发生任何严重错误,因为在捕获生产代码生成的异常并生成 HTTP 响应的过程中,您的错误处理代码可能会生成不同的东西,例如使用包含 HTML 格式错误消息的有效负载生成错误状态响应,该消息的内容类型为“text/html”,您的测试代码将无法理解该响应,它需要 json。

【讨论】:

    【解决方案2】:

    为您的设置使用以下基本测试类并将 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());
    

    【讨论】:

      猜你喜欢
      • 2021-07-28
      • 1970-01-01
      • 2016-05-28
      • 2021-04-14
      • 1970-01-01
      • 2018-02-20
      • 2015-12-20
      • 1970-01-01
      相关资源
      最近更新 更多