最近團隊內部對程序中使用大量的靜態方法
,而公司要求要有sonar掃描覆蓋率的,因為在大量使用靜態方法的地方若不mock,則覆蓋率達不到。於是網上很少的文章講解對靜態方法的mock,大多都是如何使用powermock
或 Junit
,一般對於private
或public
方法正常邏輯
是有文章講解,那么今天我就把靜態方法覆蓋的方式梳理了一下。避免每個人過來都來問口口相傳,形成文檔。
在Test方法中需要用到TimeUtil.java中的靜態方法。示例Mock操作如下:
1.添加maven配置依賴
<!-- 單元測試mock -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
<!-- 單元測試 -->
2.在Test類添加以下注解
@SuppressStaticInitializationFor("com.yuesf.utils.TimeUtil")
@PowerMockIgnore("java.lang.*")
@PrepareForTest(value = TimeUtil.class)
public class SaleOrderBizImplTest {
}
3.Test類中添加以下方法
@ObjectFactory
public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
@BeforeClass(alwaysRun = true)
public void setUp() {
MockitoAnnotations.initMocks(this);
}
4.在測試方法添加以下注解
@PrepareForTest(TimeUtil.class)
示例
@PrepareForTest(TimeUtil.class)
@Test
public void processOrderItemLabel() {
}
驗證結果: