PowerMock 访问私有域

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

– Start
假设我们有如下类。

package demo04;

import java.util.ArrayList;
import java.util.List;

public class BusinessService {
	private List<String> users = new ArrayList<>();
	
	public void addUser(String user) {
		users.add(user);
	}

}

下面我们看看访问私有字段。

package demo04;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ BusinessService.class })
public class BusinessServiceTest {

	@Test
	public void test() throws Exception {
		String testUser = "test";
		BusinessService businessService = new BusinessService();
		businessService.addUser(testUser);

		// 访问私有域
		List<String> users = Whitebox.getInternalState(businessService, "users");

		// 验证
		Assert.assertTrue(users.contains(testUser));
	}

}

– 更多参见:PowerMock 精萃
– 声 明:转载请注明出处
– Last Updated on 2019-08-17
– Written by ShangBo on 2019-08-17
– End

相关文章