如何解决获取 MockMvc 和 @MockBean 字段的空指针
我有一个测试类和一个通用的测试配置类,如下所示,我将配置注入到测试类中。
public class ControllerTest extends TestConfig {
@MockBean
private ProductListService productListService;
private String token;
@BeforeEach
public void init() throws Exception {
token = getToken();
}
@Test
public void createProductListtest() throws Exception {
ProductRequestDto productRequestDto = new ProductRequestDto();
when(productListService.createProductList(productRequestDto))
.thenAnswer(inv -> new ProductRequestDto());
String uri = "/products-lists";
MvcResult mvcResult = mvc.perform(mockmvcRequestBuilders.post(uri)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization",token)
.content(requestBody(productRequestDto))
).andReturn();
}
TestConfig 类:
@SpringBoottest(classes = {SpringBootApplication.class,TestConfig.RestTestConfig.class},properties = {"spring.main.allow-bean-deFinition-overriding=true"})
@WebAppConfiguration
@AutoConfiguremockmvc
public class TestConfig {
protected mockmvc mvc;
@Autowired
protected WebApplicationContext webApplicationContext;
@BeforeEach
public void setUp() {
mvc = mockmvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected static String requestBody(Object request) {
// return request string
}
protected String getToken() throws Exception {
// return token
}
但是在 ControllerTest
中,我收到了 productListService
和 mvc
的空指针异常。它没有正确模拟和注入吗?我哪里出错了?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。