0

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 Answers1

0

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")
    }

    
    
Karim M. Fadel
  • 338
  • 1
  • 8
  • This is not applicable for JUNIT5 Vertx as PrepareForTest is not working there . Is there other way around ? – JavaDev Dec 23 '22 at 17:33
  • You can find it in mockito-core, "org.powermock.core.classloader.annotations.PrepareForTest". I used this way before. Dependancies:- junit (4.13.2), vertx && vertx-unit (4.3.4), mockito-core (1.9.5), powermock-api-mockito (1.6.1) – Karim M. Fadel Dec 28 '22 at 11:52
  • I am migrating to JUNIT5 where pwermock does not have any support – JavaDev Jan 03 '23 at 16:55