Dart Mocking a Function

て烟熏妆下的殇ゞ 提交于 2019-12-11 03:16:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!