【发布时间】:2023-01-15 08:56:51
【问题描述】:
我正在使用 Spring Boot、MapStruct (1.5.3.Final) 和 JUnit。 我想将映射器注入服务类测试。 我不想存根这个映射器(when(..).thenReturn(...))。
我尝试了很多东西并阅读了 Stackoverflow 上的多篇文章,但我发现了任何东西。
我的映射器:
@Mapper(
componentModel = MappingConstants.ComponentModel.SPRING,
injectionStrategy = InjectionStrategy.CONSTRUCTOR
)
public interface ReservationMapper {
@Mapping(target = "id", ignore = true)
Reservation getReservationFrom(NewReservationSentByClient reservationData);
ExistingReservation getExistingReservationFrom(Reservation reservation);
}
使用此映射器的服务:
@Service
@RequiredArgsConstructor
@Slf4j
public class StandardReservationService implements ReservationService{
private final ReservationMapper reservationMapper;
...
测试类
@RunWith(SpringRunner.class)
@SpringBootTest(classes={ReservationMapper.class})
public class StandardReservationServiceTest {
@MockBean
private ReservationRepository reservationRepositoryMock;
@Autowired
private ReservationMapper reservationMapperMock;
@MockBean
private ReservationRulesRepository reservationRulesRepositoryMock;
@Autowired
private StandardReservationService service;
@ParameterizedTest
@EnumSource(ReservationSource.class)
public void ...
pom.xml
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>${org.mapstruct.version}</version>
</dependency>
<!-- TESTS -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.17</source>
<target>1.17</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-mapstruct-binding</artifactId>
<version>0.2.0</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
我试过了 :
- 在@SpringBootTest(classes={..}) 中传递 ReservationMapperImpl.class 但是当我全新安装时找不到这个实现
- 手动实例化 Reservation MapperImpl 但在我全新安装时出现同样的问题
- ...等等
如果可能的话,我不想使用@SpringBootTest,因为我正在编写单元测试,所以我不需要上下文……但我不想手动创建对象映射并将其存根。
【问题讨论】:
标签: spring-boot junit mapstruct