[英]MockBean annotation in Spring Boot test causes NoUniqueBeanDefinitionException
[英]Java/Spring-boot/Mockito @MockBean annotation work strange
在測試中,我每次運行測試時都會模擬 DateService 以具有相同的日期,但是當我在其他服務中使用 DateServie 時,模擬會一直返回 null。 這很奇怪,因為模擬在我的自定義日期時間提供程序中工作。 這是代碼:
它的工作在這里:
@Service(MyDateTimeProvider.MY_DATE_TIME_PROVIDER)
public class MyDateTimeProvider implements DateTimeProvider {
public static final String MY_DATE_TIME_PROVIDER = "MyDateTimeProvider";
@Autowired
private DateService dateService;
@Override
public Optional<TemporalAccessor> getNow() {
return Optional.of(dateService.getCurrentDate().toInstant());
}
}
@Service
public class DateService {
public Date getCurrentDate() {
return new Date();
}
}
它在用戶服務中不起作用:
@SpringBootTest
public class Test{
@MockBean
protected DateService dateService;
@BeforeEach
public void beforeEach() { Mockito.when(dateService.getCurrentDate()).thenReturn(DEFAULT_DATE_TIME.toDate());
}
...
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private DateService dateService;
private User createNewUser(final UserDto dto) {
User user = new User();
user.setEmail(dto.getEmail());
user.setRegistrationDate(dateService.getCurrentDate()); // i got null here
return userRepository.save(user);
}
}
我做錯了什么? 謝謝!
我的同事幫助了我。 我的問題是:我在帶有@PostConstuct 注釋的方法中使用了“UserService”,所以它在模擬發生之前運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.