@PostConstruct方法来自服务类,在运行JUnit案例时没有被实现



在我的MQ应用程序中,程序的流程是Route class ->服务等级->DAO类. 在服务类中,我使用了objectMapper在一个带有@PostConstruct注释的init方法中注册时间模块,如下所示:

@PostConstruct
public void init() {
mapper.registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}

但是,在使用JUnit 5测试服务类时,我模拟了DAO类并使用@InjectMocks作为服务类。但是,我在@PostConstruct注释的方法中完成的时间模块的注册没有加载到测试类中。

我试了两种方法:

  1. 在测试类中使用@PostConstruct来注册时间模块
  2. 在@BeforeEach方法中注册时间模块

两个似乎都不起作用。是否有一种方法可以将服务类中的时间注册引入JUnit或实现从服务类到测试类的@PostConstruct的方法?

您必须使用@SpringBootTest注释编写集成测试或尝试使用@JsonTest

Junit平台默认没有实现Spring bean生命周期管理器,为了正确测试SpringBoot,我建议使用集成测试。

@SpringBootTest
class MyTest {
@Test
void foo() {}
}
@SpringBootApplication
@ComponentScan(lazyInit = true) //make test runing process faster
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}

最新更新