【问题标题】:Mockito doesn't work with custom validator in SpringMockito 不适用于 Spring 中的自定义验证器
【发布时间】:2020-02-24 01:58:48
【问题描述】:

我正在使用 Mockito 来测试我在控制器类中的一个获取映射。这是我的get方法

 @PostMapping(value = "insert/carbooking")
    public ResponseEntity<Void> reservation(@Valid BookingRequest bookRequest) {
        return validate(bookRequest, carService::booking);
    }

在我的班级顶部是我的验证器

  @Autowired
  private ReservationValidator reservationValidator;

  @InitBinder("bookRequest")
    protected void bookRequestBinder(WebDataBinder binder) {
        binder.addValidators(reservationValidator);
    }

这里是 Mockito 测试方法。结果应该返回了错误的请求,因为 sin 格式错误。

@Test
    public void reservationTest2() throws Exception {

        mockMvc.perform(MockMvcRequestBuilders
                .post("insert/carbooking")
                .param("license", "data")
                .param("SIN", "202007191517")
                .accept(MediaType.MULTIPART_FORM_DATA))
                .andExpect(status().isBadRequest());
    }

但测试失败

java.lang.AssertionError: Status expected:<400> but was:<200>
Expected :400
Actual   :200

Mockito 有没有办法接收“reservationValidator”?

【问题讨论】:

  • 你没有展示你是如何获得mockMvc的。不要使用standaloneSetup,因为它确实存在这类问题(不能准确反映“非独立”环境)。
  • ``` @InjectMocks 私有 CarController carController; @BeforeEach public void setUp() { mockMvc = StandaloneSetup(clientController) .addPlaceholderValue("insert/carbooking", CAR1_ENDPOINT) } ``` 我该如何解决?
  • 你在使用 Spring Boot 吗? (还要注意,除了测试之外,避免在任何东西上使用字段注入;使用构造函数注入来避免各种错误。)
  • 然后使用@SpringBootTest @AutoConfigureMockMvc和@Autowired MockMvc
  • 您可能需要使用@MockBean 之类的东西(我使用Spock,它在将模拟作为Spring bean 插入时的设置略有不同)。

标签: java spring junit mockito springmockito


【解决方案1】:

感谢@chrylis-onstrike-,我把一切都搞定了。对于源代码,我只需要删除@Before addholders 设置方法并将其替换为Mockmvc mockmvc 上的注释@Autowired 和@MockBean 上的服务类,将客户端类放在应用程序上下文中。很遗憾我不能给他的答案打勾,因为他没有发布我的问题的答案,而是发表评论。

【讨论】:

    猜你喜欢
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多