过去几天我一直在与Dart合作进行一些单元测试。我已经看到在函数中测试函数的奇怪功能,我会模拟一个函数返回一些东西,但它不会改变先前的函数。代码和输出显示如下:
class ToBeTested {
int sum(int i, int z) {
return addOne(i) + z;
}
int addOne(int i) {
return i + 1;
}
}
test("hello", () async{
var ToBeTestedSpy = spy(new ToBeTested(), new ToBeTested(param1,param 2));
print(ToBeTestedSpy.sum(5, 10));
when(ToBeTestedSpy.addOne(5)).thenReturn(100);
print(ToBeTestedSpy.sum(5, 10));
});
输出: 16 16
为什么输出不是 16 110 即使在捣乱间谍以超越其返回100?
答案 0 :(得分:1)
间谍在mockito中已被弃用。 相反,建议手工编码部分存根(或使用代码生成技术)(参见https://github.com/dart-lang/mockito/commit/dc8ce18d6e1096d2546d1ef5afe417cd9e042aee)
我不确定你想做什么,但这是我提出的:
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
abstract class TestInterface {
int sum(int i, int z);
int addOne(int i);
}
abstract class BaseTest implements TestInterface {
int sum(int i, int z) {
return addOne(i) + z;
}
}
class Test extends Object with BaseTest implements TestInterface {
int sum(int i, int z) {
return addOne(i) + z;
}
int addOne(int i) {
return i + 1;
}
}
class MockTest extends Mock with BaseTest implements TestInterface {}
main() {
test("hello", () {
var mocked = new MockTest();
when(mocked.addOne(5)).thenReturn(100);
expect(mocked.sum(5, 10), 110);
verify(mocked.addOne(5)).called(1);
});
}