Java 使用 Mockito 进行单元测试。函数内的函数调用
Java Unit tests using Mockito. Function call within a function
假设我有以下 class :
public class Math {
public int mult(int a, int b) {
return 4;
}
public int mul (int a, int b) {
return mult(a,b);
}
}
以及下面的测试class:
public class TestMockito {
Math testMath;
@Before
public void create () {
testMath = *mock*(Math.class);
when(testMath.mult(1,2).thenReturn(2);
}
@Test
public void test() {
System.out.println(testMath.mul(1,2));
}
}
为什么在 test()
中调用的 mul(1,2)
不使用 when(testMath.mult(1,2).thenReturn(2);
?
是否有任何其他方法可以模拟在另一个正在测试的方法中使用的方法?
干杯
您通常不会模拟被测代码(除非它是一个抽象class)。
您通常会模拟与 CUT 通信的其他 classes(dependencies)。
你的测试不起作用的原因(如你所料)是模拟不是真正的对象 class(顺便说一句,这就是我们模拟它的原因....)。它由 mocking 框架派生 not 表现得像原始代码,但就像为测试配置的一样。
如果你真的想要在 mock 中调用真正的方法(这不是你大多数时候想要的)你需要在创建 mock 时告诉 mockito:
mock(ClassToBeMocked.class,Mockito.CALL_REAL_METHODS);
假设我有以下 class :
public class Math {
public int mult(int a, int b) {
return 4;
}
public int mul (int a, int b) {
return mult(a,b);
}
}
以及下面的测试class:
public class TestMockito {
Math testMath;
@Before
public void create () {
testMath = *mock*(Math.class);
when(testMath.mult(1,2).thenReturn(2);
}
@Test
public void test() {
System.out.println(testMath.mul(1,2));
}
}
为什么在 test()
中调用的 mul(1,2)
不使用 when(testMath.mult(1,2).thenReturn(2);
?
是否有任何其他方法可以模拟在另一个正在测试的方法中使用的方法?
干杯
您通常不会模拟被测代码(除非它是一个抽象class)。
您通常会模拟与 CUT 通信的其他 classes(dependencies)。
你的测试不起作用的原因(如你所料)是模拟不是真正的对象 class(顺便说一句,这就是我们模拟它的原因....)。它由 mocking 框架派生 not 表现得像原始代码,但就像为测试配置的一样。
如果你真的想要在 mock 中调用真正的方法(这不是你大多数时候想要的)你需要在创建 mock 时告诉 mockito:
mock(ClassToBeMocked.class,Mockito.CALL_REAL_METHODS);