2

如何测试是否调用了模拟函数?

我在 Mocking with Dart 上找到了这个示例- 如何测试作为参数传递的函数是否被调用?并尝试扩展它以检查是否调用了该函数。

library test2;

import "package:unittest/unittest.dart";
import "package:mock/mock.dart";

class MockFunction extends Mock {
  call(int a, int b) => a + b;
}

void main() {
  test("aa", () {

    var mockf = new MockFunction();
    expect(mockf(1, 2), 3);
    mockf.getLogs(callsTo(1, 2)).verify(happenedOnce);
  });
}

看来mockf.getLogs()结构是空的......

4

1 回答 1

1

您必须模拟方法并在日志中指定它们的名称。这是工作代码:

library test2;

import "package:unittest/unittest.dart";
import "package:mock/mock.dart";

class MockFunction extends Mock {
  MockFunction(){
    when(callsTo('call')).alwaysCall(this.foo);
  }
  foo(int a, int b) {
    return a + b;
    }
}

void main() {
  test("aa", () {    
    var mockf = new MockFunction();
    expect(mockf(1, 2), 3);
    mockf.calls('call', 1, 2).verify(happenedOnce);
  });
}

编辑: 回答类似问题:Dart How to mock a procedure

于 2014-05-29T06:37:36.057 回答