我有一个简单的REST控制器,我试图测试,测试看起来像这样:
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ModelControllerTests {
private MediaType contentType = MediaType.APPLICATION_JSON_UTF8;
private HttpMessageConverter jacksonConverter;
private MockMvc mockMvc;
@Mock
private ModelService service;
@InjectMocks
private ModelController controller;
@Autowired
private WebApplicationContext context;
@Autowired
void setConverters(HttpMessageConverter<?>[] converters) {
jacksonConverter = Arrays.stream(converters)
.filter(hmc -> hmc instanceof MappingJackson2HttpMessageConverter)
.findAny()
.orElse(null);
assertNotNull(jacksonConverter);
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = standaloneSetup(controller)
.build();
}
@Test
public void postModel_returnsModel() throws Exception {
when(service.doSomething(any())).thenReturn(new Model("cde", null));
mockMvc.perform(post("/model")
.content(json(new Model("abc", null)))
.contentType(contentType))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().json("{\"notEmpty\":\"abc\"}", true));
}
private String json(Object o) throws IOException {
var responseMessage = new MockHttpOutputMessage();
jacksonConverter.write(o, MediaType.APPLICATION_JSON_UTF8, responseMessage);
return responseMessage.getBodyAsString();
}
}
现在我遇到了依赖项和配置问题,我的application.properties:spring.jackson.default-property-inclusion=non_null
中有以下行,使用普通的mockMvc(webAppContextSetup)时工作正常,但是我想模仿ModelService
(在ModelController
中自动装配。
当使用standaloneSetup
创建MockMvc实例时,似乎没有配置,返回设置为null的字段,而且似乎使用@Mock注释的ModelService与ModelController中的模型不同,因此当postModel_returnsModel
使用错误的服务时。
我该如何解决这个问题?