【发布时间】:2019-09-17 06:17:43
【问题描述】:
我正在 Spring Boot gradle 应用程序中测试 REST API,我使用 @MockBean 的模拟服务返回 null。如果服务类中有一些自动装配的 bean(我使用了构造函数注入),则此模拟服务返回 null。
这里是示例代码(未编译,仅供理解)
@RestController
@RequestMapping("/xxx")
class TestController {
private RetriveDataService retriveDataService;
public TestControllerx(RetriveDataService retriveDataService) {
this.retriveDataService = retriveDataService;
}
@PostMapping(value = "/yyy")
public MyResponseModel myMethod(@RequestBody MyRequestModel model) {
return retriveDataService.retriveData(model);
}
}
@Service
class RetriveDataService {
private TokenService tokenService;
public RetriveDataService(TokenService tokenService) {
this.tokenService = tokenService;
}
public MyResponseModel retriveData(MyRequestModel model) {
String accessToken = tokenService.getToken().getAccessToken();
return retriveData(model, accessToken);
}
}
@RunWith(SpringRunner.class)
@WebMvcTest(TestController.class)
public class TestControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private ObjectMapper objectMapper;
@MockBean
private RetriveDataService retriveDataService;
@Test
public void testRetriveData() throws Exception {
mvc.perform(MockMvcRequestBuilders.post("/xxx/yyy").content(objectMapper.writeValueAsString(new MyRequestModel()))
.contentType(MediaType.APPLICATION_JSON_UTF8)).andDo(MockMvcResultHandlers.print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}
当我运行这个测试时,我得到以下输出(如果我的服务不需要另一个 bean,我得到预期的输出)
MockHttpServletResponse:
Status = 200
Error message = null
Headers = []
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
由于此响应,我在 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)); 线上遇到了问题。当我检查响应正文时(因为正文也是空的)
重现问题的示例项目是here
【问题讨论】:
-
您能否提供一些您的示例代码。以便我们正确理解您的问题。
-
模拟的默认行为是返回
null... 你必须在模拟上注册行为如果一个方法被调用该怎么办,如果你不这样做,它将返回@987654326 @ 或空集合等。 -
伙计们,请在更新的问题陈述中循环。
-
@M.Deinum 你的意思是我们应该像when().thenReturn()那样使用BDD吗?我也试过这个。如果是你说的情况,如何处理这种情况,它的基本用例是验证响应体的内容。
标签: spring-boot testing mockito springmockito