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

时间:2018-06-02 16:16:35

标签: java spring unit-testing spring-mvc mockmvc

我想使用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()会返回一个包含单个帐户元素的列表。

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

1 个答案:

答案 0 :(得分:1)

添加到您的测试中

when(dtoUtil.mapToDto(...)).thenCallRealMethod(); 
相关问题