我使用 MapStruct 来映射我的实体,并使用 Mockito 模拟我的对象。
我想测试一个包含 mapStruct 映射的方法。
问题是嵌套映射器在我的单元测试中始终为空(在应用程序中运行良好)
这是我的映射器声明:
@Mapper(componentModel = "spring", uses = MappingUtils.class)
public interface MappingDef {
UserDto userToUserDto(User user)
}
这是我的嵌套映射器
@Mapper(componentModel = "spring")
public interface MappingUtils {
//.... other mapping methods used by userToUserDto
这是我想测试的方法:
@Service
public class SomeClass{
@Autowired
private MappingDef mappingDef;
public UserDto myMethodToTest(){
// doing some business logic here returning a user
// User user = Some Business Logic
return mappingDef.userToUserDto(user)
}
这是我的单元测试:
@RunWith(MockitoJUnitRunner.class)
public class NoteServiceTest {
@InjectMocks
private SomeClass someClass;
@Spy
MappingDef mappingDef = Mappers.getMapper(MappingDef.class);
@Spy
MappingUtils mappingUtils = Mappers.getMapper(MappingUtils.class);
//initMocks is omitted for brevity
@test
public void someTest(){
UserDto userDto = someClass.myMethodToTest();
//and here some asserts
}
mappingDef
注入正确,但是mappingUtils
始终为空
免责声明:这不是重复的这个问题 https://stackoverflow.com/questions/53155556/junit-how-to-mock-mapstruct-nested-mapper。他正在使用 @Autowire,因此他正在加载 spring 上下文,因此他正在进行集成测试。我正在做单元测试,所以我不使用@Autowired
我不想做mappingDef
and mappingUtils
@Mock
所以我不需要做when(mappingDef.userToUserDto(user)).thenReturn(userDto)
在每个用例中