MapStruct :模拟嵌套映射器

2024-02-18

我使用 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)在每个用例中


如果您愿意使用 Spring test util,那么这相当容易org.springframework.test.util.ReflectionTestUtils.

MappingDef mappingDef = Mappers.getMapper(MappingDef.class);
MappingUtils mappingUtils = Mappers.getMapper(MappingUtils.class);

...

// Somewhere appropriate
@Before
void before() {
    ReflectionTestUtils.setField(
        mappingDef,
        "mappingUtils",
        mappingUtils
    )
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MapStruct :模拟嵌套映射器 的相关文章

随机推荐