我有一个类在其中一个方法中使用mapper来返回作为DTO列表的结果。我想使用一个真实的的mapper方法,因为它给了我检查真正功能的可能性。
这是我的测试课
@ExtendWith(MockitoExtension.class)
public class UserCardServiceTest {
@Mock
private MyCardRepository myCardRepository;
@Mock(answer = Answers.CALLS_REAL_METHODS)
private MyMapper myMapper;
@InjectMocks
private MyServiceImpl underTest;
@BeforeEach
void setUp() {
listOfExpiredUserCardEntities = new ArrayList<>(List.of(
getValidUserCardEntity()
.setExpirationDate(LocalDate.now().minusDays(1))
.setBlocked(false),
getValidUserCardEntity()
.setExpirationDate(LocalDate.now().minusWeeks(1))
.setBlocked(false),
getValidUserCardEntity()
.setExpirationDate(LocalDate.now().minusYears(1))
.setBlocked(false),
getValidUserCardEntity()
.setExpirationDate(LocalDate.now().minusMonths(1))
.setBlocked(false));
}
@Test
void shouldChangeStatusIfCardExpired() {
given(myCardRepository.findAllByUserId(1L))
.willReturn(listOfCardEntities);
assertThat(underTest.getActiveUserCardsById(1L)).isNotNull().hasSize(4);
assertThat(underTest.getActiveUserCardsById(1))
.extracting(CardDto::isBlocked)
.containsExactly(true, true, true, true)
.doesNotContainNull();
}
我的测试方法:
@RequiredArgsConstructor
public class MyServiceImpl implements MyCardService {
private final MyCardRepository myCardRepository;
private final MyMapper myMapper;
@Override
public List<CardDto> getActiveUserCardsById(final long userId) {
List<CardEntity> listOfEntities = myRepository.findAllByUserId(userId);
listOfEntities.stream().filter(validationService::isCardExpired)
.forEach(userCard -> userCard.setBlocked(true));
List<CardEntity> sorted = listOfEntities.stream()
.sorted(o -> o.getName().toUpperCase())
.toList();
return myMapper
.listOfCardEntitiesToCardDto(sorted);
}
但结果我得到:
java.lang.AssertionError:
Expected size: 4 but was: 0 in:
[]
有谁能告诉我如何调用一个真实的的mapstructMap器方法,但没有准备好答案吗?是否可以只使用@ExtendWith(MockitoExtension.class)?
1条答案
按热度按时间n6lpvg4x1#
我在我的项目中遇到了同样的问题。我正在使用以下解决方案:
这只适用于
@ExtendWith(MockitoExtension.class)
,不需要启动整个SpringBoot上下文;)