PowerMock Mock 静态方法

x33g5p2x  于2021-12-28 转载在 其他  
字(1.3k)|赞(0)|评价(0)|浏览(282)

– 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

相关文章