我有一个class A
,它具有静态方法testA(String auditUser, Timestamp timestamp)
,如果class B
为auditUser
,则该方法调用admin
的静态方法。我正在尝试为A类编写测试。如何验证B的静态方法是否被调用?
class A {
public static testA(String auditUser, Timestamp timestamp) {
if ("admin".equalsIgnoreCase(auditUser) {
B.testB(timestamp);
}
}
}
class B {
public static testB(Timestamp timestamp) {
//...some logic...//
}
}
我为您的静态方法添加了void以进行编译。
@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...//
}
}
并且不要忘记Maven依赖项
<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>