我有 MyClass,我正在为每个方法(Method1Test)做一个测试类
public class MyClass {
public int method1(){
int a = method2();
return a;
}
public int method2(){
return 0;
}
}
@RunWith(MockitoJUnitRunner.class)
public class Method1Test {
@InjectMocks
private MyClass myClass = new MyClass();
@Before
public void setup(){}
@Test
public void test01(){
Mockito.when(myClass.method2()).thenReturn(25);
int a = myClass.method1();
assertTrue("We did it!!!",a==25);
}
}
问题是我无法模拟对 method2 的调用以使其返回不同的值。 Mockito 语句不起作用。
非常感谢^_^
最佳答案
您必须在被测类上创建一个 spy ,并通过重新定义 spy 的 method2()
行为来部分模拟它
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class Method1Test {
private MyClass myClass = new MyClass();
@Test
public void test01(){
//given
MyClass spy = spy(myClass); //create a spy for class-under-test
when(spy.method2()).thenReturn(25); //partially override behavior of the spy
//when
int a = spy.method1(); //make the call to method1 of the _spy_!
//then
assertEquals(25, a);
}
}
除此之外,您的测试既不需要 Mockito Runner,也不需要 @InjectMocks
,因为您不需要将 @Mock
带注释的模拟注入(inject)到被测类。
此外,仅当断言的条件不满足时,才会显示assertTrue
语句中的消息。所以它应该至少“我们失败了!!!” ;)
关于java - 如何模拟从 Junit 调用内部方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37095096/