Java 如何使用Mockito/Powermock测试具有构造函数参数的类的方法
我有一个Mockito/PowerMockito问题 要测试的类别如下所示:Java 如何使用Mockito/Powermock测试具有构造函数参数的类的方法,java,mockito,junit4,powermockito,Java,Mockito,Junit4,Powermockito,我有一个Mockito/PowerMockito问题 要测试的类别如下所示: public class ClassToTest { private String string; public ClassToTest(String s) { this.string = s; } public String concatenate() { return string.concat(" - Done!");
public class ClassToTest {
private String string;
public ClassToTest(String s) {
this.string = s;
}
public String concatenate() {
return string.concat(" - Done!");
}
public ClassToTest create(String s) {
return new ClassToTest(s);
}
}
我编写的测试类:
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(ClassToTest.class)
public class ClassToTestTest {
@Test
public void concatenate() throws Exception {
ClassToTest classToTest = Mockito.mock(ClassToTest.class);
PowerMockito.whenNew(ClassToTest.class).withArguments(Mockito.anyString()).thenReturn(classToTest);
classToTest.concatenate();
}
}
问题-如何从测试类中设置名为“string”的实例变量的值,以便可以测试concatenate方法(concatenate方法使用构造函数初始化的“string”变量)。当前调试点甚至不在concatenate()方法中。我需要使用mockito/powermock进行此操作
注意-我给出的示例是我实时面临的问题的表示
任何线索都会帮助我
提前感谢!!您的测试毫无意义,原因有几个
ClassToTest tested = new ClassToTest("test"); // create instance
String concatResult = tested.concatenate(); // call method under test
assertThat(concatResult).isEqualTo("test - Done"); // verify result
不需要模仿任何东西。如果你想测试create
方法(顺便说一句,我看不出有什么意义),你可以这样做
ClassToTest tested = new ClassToTest(""); // the String is never used anyway
ClassToTest created = tested.create("test"); // call method under test
assertThat(created.concatenate()).isEqualTo("test - Done"); // verify
如果您模拟正在测试的类,则不会测试类的行为,而只测试模拟的结果
不要这样做
ClassToTest mock = mock(ClassToTest.class);
ClassToTest other = mock(ClassToTest.class);
when(mock.create(anyString()).thenReturn(other);
when(other.concatenate(anyString()).thenReturn("expected");
ClassToTest created = mock.create("test");
String result = created.concatenate("lala");
assertThat(result).isEqualTo("expected"); // duh
您不需要模拟要测试的类。