xxx_Beryl_xxx
xxx_Beryl_xxx

Reputation: 1

@PostConstruct method from service class, is not being implemented while running JUnit cases

In my MQ application, the flow of the program is Route class -> Service class -> DAO class. In the service class, I have used an objectMapper to register time module in an init method annotated with @PostConstruct as follows :

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

But while testing the service class with JUnit 5, I have mocked the DAO class and used @InjectMocks for the service class. But, the registration of time module which I had done in the method annotated with @PostConstruct is not loaded to the test class.

I tried two ways :

  1. Using @PostConstruct in test class for registering time module.
  2. Registering time module in @BeforeEach method.

Both don't seem to work. Is there a way to bring in the time registration in service class to the JUnit or a way to implement the @PostConstruct from service class to the test class?

Upvotes: 0

Views: 616

Answers (1)

Gannebal Barka
Gannebal Barka

Reputation: 83

You must write or Integration Test with @SpringBootTest annotation or will try use @JsonTest

Junit platform by default not implemented Spring beans lifecycle manager and for correctly testing SpringBoot i recommend use Integration Test.

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

Upvotes: 1

Related Questions