我无法控制我想要测试的方法中的变量。在此示例中,正在测试的方法的输入是模拟或可注入的对象,但如果您尝试对其执行任何操作,则会获得Null *异常。
正在测试的类和方法:
public class SomeClass {
public SomeClass() {}
public void myMethod(InputClass input) {
//how do I set this field so that no matter what, I don't get an exeption?
long someLong = Long.parseLong(input.getSomeLong());
// how do I prevent the NumberFormatException when Long.parseLong() is called in this situation?
SomeInnerClass innerClass = SomeInnerClass(Long.parseLong(input.getSomeLong()));
// how do I prevent the NumberFormatException when Long.parseLong() is called in this situation?
innerClass.doStuff(Long.parseLong(input.getSomeLong()));
// ...
}
}
测试类:
public class TestSomeClass {
@Tested private SomeClass classBeingTested;
@Injectable SomeInnerClass innerClass;
@Injectable InputClass input; // doesn't matter if I use @mocked here
@Test
public void shouldTestSomething() {
new NonStrictExpectations() {{
// some expectations with innerClass...
}};
classBeingTested.myMethod(input); // at this point I would get an error from Long.parsLong()
// ...
}
}
我希望能够忽略我正在测试的方法中代码的某些部分的错误。在这种特定情况下,我根本不关心Long.parseLong()错误。我目前没有尝试测试,但它正在妨碍真正的测试。如何创建一个虚假对象,代替导致问题的对象,以便在测试方法的其他部分时可以忽略它?
答案 0 :(得分:0)
请使用以下代码并检查是否有帮助。您需要在项目中添加对mockito的依赖。一个重要的想法是确保在测试类中使用@RunWith(MockitoJUnitRunner.class)
。
@RunWith(MockitoJUnitRunner.class)
public class TestSomeClass {
@Tested private SomeClass classBeingTested;
@Injectable SomeInnerClass innerClass;
@Mock
InputClass input; // doesn't matter if I use @mocked here
@Test
public void shouldTestSomething() {
new NonStrictExpectations() {{
// some expectations with innerClass...
}};
Mockito.when(input).getSomeLong().thenReturn("11").thenReturn("11");//This will return 11 in place of input.getSomeLong()for 2 times
classBeingTested.myMethod(input); // In this case yoou will not get an error from Long.parsLong()
// ...
}
}
=============================================== ======
使用JMockit:
import org.junit.Test;
import mockit.Injectable;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import mockit.Tested;
public class SomeClassTest {
@Tested
private SomeClass classBeingTested;
@Injectable
SomeInnerClass innerClass;
@Mocked
InputClass input;
@Test
public void shouldTestSomething() {
new NonStrictExpectations() {
{
input.getSomeLong();
returns("11");
}
};
classBeingTested.myMethod(input);
// ...
}
}