Vertx JUNIT5 issue during mocking

323 Views Asked by At

I am unable to mock static classes for Vertx JUNIT5. Added all dependencies as well in pom.xml for Vertx JUNIT5.



Code Snippet:

@ExtendWith (VertxExtension.class) 

VertxTestClass {

    @BeforeEach
     public void beforeEach(Vertx vertx,VertxTestContext ctx)
    { 
        vertx=Vertx.vertx(options);
        Mockito.mockstatic(Placeholder.java);
        when (Placeholder.getValue(Mockito.anyString()).thenReturn("value")
        vertx.deployVerticle(MyVerticle.class.getaName()).onSuccess(ok->testContext.completeNow())
    }

}

Main Class: 

MyVerticle extends AbstractVerticle{

    @Override Public void start(Promise<Void> appState)
    { …. 
      Placeholder.getValue(“MyValue”);  // this is always returning NULL even this is mocked in test 
                                        // class
        … 
    }

}

When verticle is deployed the start method MyVerticle Class is invoked. But even though Placeholder class is mocked then also Placeholder.getValue("MyValue") is returned as NULL.

Unable to figure out how to do that mocking. I have tried with Mocked Static as well but that also does not help. To me it looks like when vertx deploy verticle is called then the start method is not being invoked directly but it will be invoked by Vertx. so somewhere that scope is lost and whatever mocking is done in test class is lost. Unable to figure out a way. Any help is appreciated

1

There are 1 best solutions below

3
On

Nowadays, using Mockito to mock static methods is very easy.

you should declare dependency mockito-inline

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-inline -->
<dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-inline</artifactId>
   <version>4.10.0</version>
   <scope>test</scope>
</dependency>

then

@PrepareForTest({ Placeholder.class })
VertxTestClass {
    @BeforeEach
    public void beforeEach() {
         mockStatic(Placeholder.class);
         when (Placeholder.getValue(Mockito.anyString()).thenReturn("value")
    }