– Start
假设我们有如下类。
package demo01;
import java.util.List;
public class BusinessService {
public List<String> getAllUser() {
return BusinessUtil.getAllUser();
}
}
它调用如下的静态方法。
package demo01;
import java.util.Arrays;
import java.util.List;
public class BusinessUtil {
public static List<String> getAllUser() {
return Arrays.asList("zhangsan", "lisi");
}
}
下面我们看看如何测试。
package demo01;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ BusinessUtil.class })
public class BusinessServiceTest {
@Test
public void test() {
List<String> expected = Arrays.asList("test", "test2");
// Mock 静态方法
PowerMockito.mockStatic(BusinessUtil.class);
Mockito.when(BusinessUtil.getAllUser()).thenReturn(expected);
// 调用测试方法
BusinessService businessService = new BusinessService();
List<String> users = businessService.getAllUser();
// 验证
Assert.assertArrayEquals(expected.toArray(), users.toArray());
}
}
– 更多参见:PowerMock 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-08-16
– Written by ShangBo on 2019-08-16
– End
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/shangboerds/article/details/99685266
内容来源于网络,如有侵权,请联系作者删除!