mockito模拟私有方法

用到powmock
注意点:
1 @RunWith(PowerMockRunner.class)
2 @PrepareForTest(PrivateObject.class)
3   PrivateObject obj = PowerMockito.spy(new PrivateObject()); 这里用spy
4   PowerMockito.when(obj, "name").thenReturn("private");  name是方法名



package com.eyu.ahxy.module.staticd;

public class PrivateObject {

	private String name() {
		return "test";
	}

	public String name2() {
		return name();
	}

}





package com.eyu.ahxy.module.staticd;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
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(PrivateObject.class)
public class PrivateTest {

	@Test
	public void test1() throws Exception {
		PrivateObject obj = PowerMockito.spy(new PrivateObject());
		PowerMockito.when(obj, "name").thenReturn("private");
		String result = obj.name2();
		assertThat(result, equalTo("private"));
	}

}




powmock的依赖
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.1</version>
<scope>test</scope>
</dependency>

你可能感兴趣的:(mockito)