模型映射器mock在spring引导单元测试中返回null对象



我正在尝试使用MockMvc和Mockito为应用程序中的rest控制器类编写单元测试。我有实体类的DTO类,作为控制器方法的输入。控制器方法将这个DTO对象映射到实体类中,并使用我的服务类将其持久化。持久化后,通过映射服务类方法返回的对象来创建一个新的DTO类,并在ResponseEntity对象中返回此DTO。在我的单元测试中,我使用@MockBean注释模拟了服务类和ModelMapper类。我还为模拟类的方法设置期望的返回值。但是当我运行测试时,我看到响应主体是空的,我认为这是因为mock映射器没有正确返回DTO对象。有人能帮我让mock映射器正确返回对象,这样我的测试就通过了吗?谢谢

这是控制器代码:

@RequestMapping(value = "", method=RequestMethod.POST)
public ResponseEntity<BranchDto> addBranch(@RequestBody BranchDto branchDto) {
Branch branch = modelMapper.map(branchDto, Branch.class);
Branch addedBranch = branchService.addBranch(branch);
return new ResponseEntity<>(modelMapper.map(addedBranch, BranchDto.class), HttpStatus.CREATED);
}

这是单元测试代码:

@Autowired
private MockMvc mockMvc;
@MockBean
private BranchService branchService;
@MockBean
private ModelMapper mockModelMapper;
@Test
public void testAddBranch() throws Exception{
BranchDto mockBranchDtoToAdd = new BranchDto();
mockBranchDtoToAdd.setBranchName("TestBranch");
mockBranchDtoToAdd.setContactNumber("12345");
mockBranchDtoToAdd.setEmailId("test@abc.com");
mockBranchDtoToAdd.setCity("TestCity");
Branch mockBranchToAdd = new Branch();
mockBranchToAdd.setBranchName("TestBranch");
mockBranchToAdd.setContactNumber("12345");
mockBranchToAdd.setEmailId("test@abc.com");
mockBranchToAdd.setCity("TestCity");
Branch mockAddedBranch = new Branch();
mockAddedBranch.setBranchName("TestBranch");
BranchDto mockAddedBranchDto = new BranchDto();
mockAddedBranchDto.setBranchName("TestBranch");
mockAddedBranchDto.setContactNumber("12345");
mockAddedBranchDto.setEmailId("test@abc.com");
mockAddedBranchDto.setCity("TestCity");
Mockito.when(mockModelMapper.map(mockBranchDtoToAdd, Branch.class)).thenReturn(mockBranchToAdd);
Mockito.when(branchService.addBranch(mockBranchToAdd)).thenReturn(mockAddedBranch);
Mockito.when(mockModelMapper.map(mockAddedBranch, BranchDto.class)).thenReturn(mockAddedBranchDto);

ObjectMapper mapper = new ObjectMapper();
String mockBranchDtoToAddStr = mapper.writeValueAsString(mockBranchDtoToAdd);
System.out.println(mockBranchDtoToAddStr);
mockMvc.perform(post("/branches").contentType(MediaType.APPLICATION_JSON).content(mockBranchDtoToAddStr))
.andExpect(MockMvcResultMatchers.status().isCreated())
.andExpect(MockMvcResultMatchers.jsonPath("$.branchName").value("TestBranch"));
}

经过大量挖掘,我发现

Mockito.when(branchService.addBranch(mockBranchToAdd)).thenReturn(mockAddedBranch);

没有正确设置模拟对象。在when()方法中,我将这一行更改为使用any(),此后效果良好。这是更新后的代码:

Mockito.when(branchService.addBranch(org.mockito.ArgumentMatchers.any())).thenReturn(mockAddedBranch);
Mockito.when(mockModelMapper.map(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())).thenReturn(mockAddedBranch);

最新更新