【发布时间】:2019-09-05 06:44:56
【问题描述】:
我正在尝试测试一个控制器,以便它根据我在对象上定义的验证器触发对请求主体对象的验证。下面是相关的类。 如果您注意到我的测试方法,我期待基于定义的验证器的错误请求,但由于某种原因,它直接尝试执行服务,这不是预期的,因此我没有为服务定义任何模拟,因此,我获取 NullPointerException,因为服务对象在被模拟时为空。 我尝试根据谷歌搜索和stackoverflowed的一些建议将WebMvcTest替换为SpringBootTest,但没有任何帮助。可能的原因是什么?
请求对象
@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());
}
}
【问题讨论】:
-
为什么你的 bean 顶部有 @Validated 注解?
-
我实际上启用了组验证,因此实际属性被分成组,它们将仅作为该组的一部分进行验证
标签: java spring-boot bean-validation spring-boot-test