【问题标题】:Could not autowire Mapper from mapStruct无法从 mapStruct 自动装配 Mapper
【发布时间】:2020-06-05 20:25:10
【问题描述】:

我无法在测试中从 mapstruct 自动装配 Mapper。在使用 SpringRunner.class 进行测试时它可以,但是当我尝试使用 MockitoJunitRunner 时它是不可能的。

@Mapper(componentModel = "spring", uses = {})
public interface UserMapper {
    UserMapper MAPPER = Mappers.getMapper(UserMapper.class);

    User mapToUser(UserDto userDto);

    UserDto mapToUserDto(User user);

    List<UserDto> mapToUserDtoList(List<User> userList);
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class nowyTest {
    @Spy
    private UserMapper userMapper;

    private User createUser() {
        return User.builder()
                .firstName("Steve")
                .lastName("Jobs")
                .login("SteveJobs")
                .password("password")
                .role(UserRole.ROLE_ADMIN)
                .build();

    }

    @Test
    public void testMapper() {
        User user = createUser();
        UserDto userDto = userMapper.mapToUserDto(user);

        System.out.println(userDto);
        Assert.assertEquals(userDto.getFirstName(), "Steve");
    }

}

它返回 NPE :(

【问题讨论】:

    标签: java spring spring-boot testing integration-testing


    【解决方案1】:

    您是否尝试过包含注释@Import(yourClass)?在这种情况下:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @Import(UserMapper.class)
    public class nowyTest {
       ...
    

    您可以查看this tutorial 了解有关如何在 SpringBoot 测试中启动 bean 的更多信息。

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 2018-12-05
      • 2014-11-11
      • 1970-01-01
      • 2021-09-28
      • 1970-01-01
      • 2021-07-17
      • 2012-01-27
      • 2016-10-09
      相关资源
      最近更新 更多