-1

I have a class A which has a static method testA(String auditUser, Timestamp timestamp) which calls a static method of class B if auditUser is admin. I am trying to write test for class A. How can I verify the static method of B got called or not?

class A {
  public void static testA(String auditUser, Timestamp timestamp) {
    if ("admin".equalsIgnoreCase(auditUser) {
      B.testB(timestamp);
    }
  }
}

class B {
  public void static testB(Timestamp timestamp) {
  //...some logic...//
  }
}
ashokramcse
  • 2,841
  • 2
  • 19
  • 41
Appu2506
  • 1
  • 2

2 Answers2

0

I add void to your static method for compile.

@SpringBootTest
@RunWith(PowerMockTestRunner.class)
@PrepareForTest(value = B.class)
public class TestClass {

    @Test
    public void testBAdmin() {
        String auditUser = "admin";
        Timestamp timestamp = new Timestamp(1577447182l);

        PowerMockito.mockStatic(B.class);
        //You can mock method here, if you need return value like this
        //when(B.testB(timestamp)).thenReturn("some_value");

        A.testA(auditUser, timestamp);

        PowerMockito.verifyStatic(B.class);
        B.testB(timestamp);
    }
    @Test
    public void testBNotAdmin() {
        String auditUser = "not_admin";
        Timestamp timestamp = new Timestamp(1577447182l);

        PowerMockito.mockStatic(B.class);
        //You can mock method here, if you need return value like this
        //when(B.testB(timestamp)).thenReturn("some_value");

        A.testA(auditUser, timestamp);

        PowerMockito.verifyZeroInteractions(B.class);
    }
}
class A {
    public static void testA(String auditUser, Timestamp timestamp) {
        if ("admin".equalsIgnoreCase(auditUser)) {
            B.testB(timestamp);
        }
    }
}

class B {
    public static void testB(Timestamp timestamp) {
//...some logic...//
    }
}

And don't forget about maven dependency

<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-api-mockito2</artifactId>
  <version>2.0.0-beta.5</version>
</dependency>
<dependency>
  <groupId>org.powermock</groupId>
  <artifactId>powermock-module-junit4</artifactId>
  <version>2.0.0-beta.5</version>
</dependency>
AnnKont
  • 424
  • 4
  • 17
0

Please follow these steps:

  1. Add @PrepareForTest({ClassA.class, ClassB.class})
  2. These use PowerMockito.mockStatic(ClassA.class);, PowerMockito.mockStatic(ClassB.class);
  3. The use PowerMockito.when(ClassA.testA(ArgumentMatchers.anyString(), ArgumentMatchers.any())).thenReturn(PowerMockito.when(ClassB.testB(ArgumentMatchers.any()))).thenReturn(any());
ashokramcse
  • 2,841
  • 2
  • 19
  • 41