– Start
假设我们有如下类。
package demo02;
import java.util.Arrays;
import java.util.List;
public class BusinessService {
public List<String> getAllUser() {
// 调用 private 方法
return users();
}
private List<String> users() {
return Arrays.asList("zhangsan", "lisi");
}
}
下面我们看看如何测试。
package demo02;
import java.util.Arrays;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ BusinessService.class })
public class BusinessServiceTest {
@Test
public void test() throws Exception {
List<String> expected = Arrays.asList("test", "test2");
// Mock 私有方法
BusinessService businessService = PowerMockito.spy(new BusinessService());
PowerMockito.doReturn(expected).when(businessService, "users");;
// 调用测试方法
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/99685350
内容来源于网络,如有侵权,请联系作者删除!