Java/Spring-boot/Mockito @MockBean 注释工作奇怪

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();
    }

}

它在 UserService 中不起作用:

@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”,所以它在模拟发生之前 运行。