问题
How do I test that a mocked function was called?
I found this example on Mocking with Dart - How to test that a function passed as a parameter was called? and tried to extend it to check if the function was called.
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);
});
}
It appears that the mockf.getLogs() structure is empty...
回答1:
You must mock methods and specify their names in the log. Here's working code:
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);
});
}
edit: answer to the similar question: Dart How to mock a procedure
来源:https://stackoverflow.com/questions/23925384/dart-mocking-a-function