繁体   English   中英

MockMvc REST控制器-始终返回空主体

[英]MockMvc REST controller - always returns empty body

我想使用MockMvc测试我的REST控制器,但是我总是得到一个空的响应。

我的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());
}}

accountService when mock按预期方式工作时,调用accountService.findAll()返回带有单个account元素的列表。

与我使用的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());
    }

运行测试将导致MockHttpServletResponse的主体为null

它对于我的普通(具有模型的非休息状态)控制器可以完美地工作,唯一的区别是它不使用DtoUtil

这可能是它不断返回null的原因吗?

编辑:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM