我需要在我测试的类的父类中模拟一个受保护的方法,但是父类在不同的包中,所以我的测试类无法访问该方法,因此我无法模拟它。没有重构
就必须有解决这个问题的方法我需要使用Powermock和Mockito。这是JARs
这是遗留代码,所以我无法重构,但这里是简化代码。
Parent.java
package parent;
public class Parent {
// Want to mock this protected parent method from different package
protected String foo() {
String someValue = null;
// Logic setting someValue
return someValue;
}
}
Child.java
package child;
import parent.Parent;
public class Child extends Parent {
String fooString = null;
public String boo() {
this.fooString = this.foo();
String booString = null;
// Logic setting booString
return booString;
}
}
ChildTest.java
package child;
import static org.mockito.Mockito.spy;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import parent.Parent;
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Parent.class, Child.class })
public class ChildTest {
// Class Under Test
Child cut;
@Before
public void setUp() throws Exception {
// Partial mock to mock methods in parent class
cut = spy(new Child());
}
@Test
public void testBoo() {
// TODO: Need to mock cut.foo() but can't figure out how.
// Following gives me this error: The method foo() from the type Parent is not visible
Mockito.when(((Parent)cut).foo()).thenReturn("mockValue");
// Test
cut.boo();
// Validations
Assert.assertEquals(cut.fooString, "mockValue");
}
}
答案 0 :(得分:5)
只需创建一个新类来测试扩展您要测试的类,并在那里覆盖您的方法。
那看起来像那样:
public class ChildForTest extends Child{
@Override
protected String foo() {
//mock logic here
}
}
编辑: 如果要避免新的类定义,可以使用匿名类
@Before
public void setUp() throws Exception {
// Partial mock to mock methods in parent class
cut = new Child(){
@Override
protected String foo(){
//mock logic here
return "";
}
};
}
答案 1 :(得分:3)
您可以使用PowerMock来模拟任何公共方法。
@RunWith(PowerMockRunner.class)
public class ChildTest {
@Test
public void testBoo() throws Exception {
//given
Child child = PowerMockito.spy(new Child());
PowerMockito.when(child, "foo").thenReturn("mockValue");
//when
String boo = child.boo();
//then
Assert.assertEquals("boo+mockValue", boo);
}
}