SpringBootTest/WebMvcTest 不会在请求正文上调用验证器



我正在尝试测试控制器,以便它根据我在对象上定义的验证器触发对请求正文对象的验证。以下是相关类。 如果您注意到我的测试方法,我预计会根据定义的验证器发出错误请求,但由于某种原因,它直接尝试执行服务,这是意料之外的,因此我没有为服务定义任何模拟,因此,我得到一个 NullPointerException,因为服务对象在被模拟时为空。 我尝试将WebMvcTest替换为SpringBootTest,基于我用谷歌搜索和stackoverflow的一些建议,但没有任何帮助。可能的原因是什么?

请求对象

@Validated
public class RequestBean implements Serializable {
private static final long serialVersionUID = -8976713543478074839L;
@NotNull
private Long id;
@NotNull
private String name;
@NotEmpty
private List<Long> statusIds;
// getters and setters
}

控制器

@RestController
public class SomeController {
@Autowired
private SomeService service;
@PostMapping(value = "/resources", produces = MediaType.APPLICATION_JSON_VALUE)
public List<VerDealProductBean> fetchResources(
@Valid @RequestBody RequestBean request)
throws SomeException {
return service.doSomething(request);
}

控制器测试

@RunWith(SpringRunner.class)
@WebMvcTest(SomeController.class)
@ActiveProfiles("test")
public class SomeControllerTest {
private MockMvc mockMvc;
@MockBean
private SomeService service;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(SomeController.class)
.build();
}
@Test
public void testFetchResourcesWithNoInput() throws Exception {
String request = "{"id": null}";
mockMvc.perform(post("/resources")
.contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
.content(request))
.andDo(print())
.andExpect(status().isBadRequest());
}

}

也许你缺少一个软件包javax.el

http://hibernate.org/validator/documentation/getting-started/

<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.el</artifactId>
<version>3.0.1-b09</version>
</dependency>

最新更新