Dart如何模拟程序 [英] Dart How to mock a procedure

查看:128
本文介绍了Dart如何模拟程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进行嘲笑程序(如同函式一样,请参阅这里



例如,给定以下typedef和过程,

  

int useAdder(加法器){
返回加法器(1,2);
}

如何写一个模拟器,让你测试userAdder过程调用你的mocked函数?



这是我的尝试,但它失败,并显示测试失败的消息:Caught null对象没有方法'call' 。

  class MyMock extends Mock {
MyMock b $ b when(callsTo('call'))。alwaysCall(this.foo);
}
int foo(int a,int b)=> a + b;
}

void main(){

test(bb,(){
var mockf = new MyMock b expect(useAdder(mockf.call),3);
mockf.getLogs(callsTo('call',1,2))。verify(happensOnce);
}
}

如果我更改



< pre class =lang-dart prettyprint-override> expect(useAdder(mockf.call),3)

  expect(useAdder(mockf.foo),3); 

方法调用不会出现在日志中

解决方案

我的尝试

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

typedef int Adder(int a,int b);

int useAdder(加法器){
返回加法器(1,2);
}

类MyMock扩展Mock {
MyMock(){
when(callsTo('call'))。alwaysCall(this.foo);
}
int foo(int a,int b)=> a + b;

int call(int a,int b)=> super.call(a,b);

}

void main(){

test(bb,(){
var mockf = new MyMock ;
expect(useAdder(mockf as Adder),3);
mockf.getLogs(callsTo('call',1,2))。verify(happenedOnce);
}
}

似乎调用方法实际上存在使MyMock被接受为Adder 。


How do I go about mocking a procedure (as apposed to a function see here)

For example, given the following typedef and procedure,

typedef int Adder(int a, int b);

int useAdder(Adder adder) {
  return adder(1, 2);
}

How could you write a mock that would allow you to test that the userAdder procedure called you mocked function?

This was my attempt, but it fails with the message that test failed: Caught The null object does not have a method 'call'.

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

void main() {

  test("bb", () {
    var mockf = new MyMock();
    expect(useAdder( mockf.call), 3);
    mockf.getLogs(callsTo('call', 1, 2)).verify(happenedOnce);
  });
}

If I change

 expect(useAdder( mockf.call), 3);

to

 expect(useAdder( mockf.foo), 3);

the method call does not appear in the log

解决方案

My attempt

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

typedef int Adder(int a, int b);

int useAdder(Adder adder) {
  return adder(1, 2);
}

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

  int call(int a, int b) => super.call(a, b);

}

void main() {

  test("bb", () {
    var mockf = new MyMock();
    expect(useAdder(mockf as Adder), 3);
    mockf.getLogs(callsTo('call', 1, 2)).verify(happenedOnce);
  });
}

It seems the call method has to actually exist to make MyMock being accepted as Adder.

这篇关于Dart如何模拟程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆