[英]MockMvc REST controller - always returns empty body
I would like to test my REST controller using MockMvc but I always get an empty body response. 我想使用MockMvc测试我的REST控制器,但是我总是得到一个空的响应。
My AccountControllerUnitTest
looks like this: 我的
AccountControllerUnitTest
看起来像这样:
@RunWith(SpringRunner.class)
@WebMvcTest(AccountRestController.class)
public class AccountRestControllerUnitTests {
@Autowired
private MockMvc mockMvc;
@MockBean(name = "dtoUtil")
private DtoUtil dtoUtil;
@MockBean
private AccountService accountService;
@Test
public void canRetrieveAll() throws Exception {
when(accountService.findAll())
.thenReturn(Collections.singletonList(AccountTestFixture.createAccount()));
this.mockMvc.perform(get("/accounts")).andDo(print())
.andExpect(status().isOk());
}}
The accountService when mock
works as expected, calling accountService.findAll()
returns a list with a single account element. accountService when mock
按预期方式工作时,调用accountService.findAll()
返回带有单个account元素的列表。
With my used AccountRestController
being: 与我使用的
AccountRestController
是:
@RestController
@AllArgsConstructor
@RequestMapping("/accounts")
public class AccountRestController {
private AccountService accountService;
@Qualifier(dtoUtil)
private DtoUtil dtoUtil;
@GetMapping
public List<AccountDto> getAccounts() {
return accountService.findAll().stream()
.map(dtoUtil::mapToDto)
.collect(Collectors.toList());
}
Running the test will result in a MockHttpServletResponse
with a body that is null
. 运行测试将导致
MockHttpServletResponse
的主体为null
。
It works flawlessly for my normal (non-rest that has a model) controller, the only difference being that it doesn't use the DtoUtil
. 它对于我的普通(具有模型的非休息状态)控制器可以完美地工作,唯一的区别是它不使用
DtoUtil
。
Could that be the reason for it constantly returning null? 这可能是它不断返回null的原因吗?
edit: 编辑:
The DtoUtil
: DtoUtil
:
@Component
public class DtoUtil{
@Autowired
private ModelMapper mapper;
public AccountDto mapToDto(Account account) {
return modelMapper.map(account, AccountDto.class);
}
}
添加到您的测试
when(dtoUtil.mapToDto(...)).thenCallRealMethod();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.