5

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

Community
  • 1
  • 1
richard
  • 2,887
  • 5
  • 26
  • 36
  • You should rename this question to "Dart Mocking a Function" and previous one to "Dart Mocking a call method" so it will be more helpful to the Dart community. – JAre May 29 '14 at 23:52

2 Answers2

2

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.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • This certainly works, but it is as ugly as sin! You have to define two methods, one that does the work, the other that calls the when() and then define a when to get logging! All this for a language that is highly procedural orientated. I hope the writes of the mock package come up with something simpler!!!! – richard May 30 '14 at 09:23
  • I don't like it either. I just found https://code.google.com/p/dart/issues/detail?id=18341 seems there are plans to improve it. See also the linked issue https://code.google.com/p/dart/issues/detail?id=18334 – Günter Zöchbauer May 30 '14 at 09:25
  • @richard yeah it's pretty ugly. And it gets even worse because Dart doesn't support variable number of arguments. – JAre May 30 '14 at 09:36
  • Why You use @proxy annotation? I don't see any errors or warnings without it. – JAre May 30 '14 at 12:15
  • 1
    This might be redundant, didn't think much about it. As far as I remember it was necessary a while ago to avoid warnings. – Günter Zöchbauer May 30 '14 at 12:16
  • @GünterZöchbauer Just checked. `Mock` class has `@proxy` annotation and it propagates through inheritance. So it is redundant. – JAre May 31 '14 at 07:42
  • Ok, thanks for the feedback. I think this was the bug which is obviously fixed, that the analyzer didn't recognize the annotation on super classes. – Günter Zöchbauer May 31 '14 at 08:27
2

I updated my code with the core idea from the Günter Zöchbauer's solution.

library functionMockTest;

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


typedef int BinaryIntToInt(int a, int b);
typedef double BinaryIntToDouble(int a, int b);
typedef int DoubleIntToInt(double a, int b);


int useBinaryIntToInt(BinaryIntToInt adder) => adder(1, 2);


void main() {
  test('Mock [min] function from the "dart:math"', () {
    var min = new FunctionMock(math.min);
    expect(min(2,1), 1);
    expect(min(1,2), 1);
    min.calls('call', 1, 2).verify(happenedOnce);
  });

  test("Function Mock", () {
    var adder2 = new FunctionMock<BinaryIntToInt>((a,b) => a + b);
    var adder3 = new FunctionMock((a,b,c) => a + b + c);
    expect(adder2 is Function, true);
    expect(useBinaryIntToInt(adder2), 3);
    expect(adder3(1,2,3), 6);
    adder2.calls('call', 1, 2).verify(happenedOnce);
  });
  group("Type check on function mocks:", (){
    test("Should throw [TypeError] \n "
        "if function has wrong number of arguments", () {
      TypeError error;
      try {
        var adder3 = new FunctionMock<BinaryIntToInt>((a,b,c) => a + b + c);
        }
      catch(exception) {
        expect(exception is TypeError, true);
        error = exception;
        }
      expect(error != null,  true);
    });
    test("Should throw [TypeError] \n "
        "if function has wrong type of arguments", () {
      TypeError error;
      try {
        var adder3 = new FunctionMock<BinaryIntToInt>((double a,b) => 10);
        }
      catch(exception) {
        expect(exception is TypeError, true);
        error = exception;
        }
      expect(error != null,  true);
    });
    test("Doesn't throw on typedef mismatch \n"
        "without type annotation", () {
      BinaryIntToDouble foo = (c,d) => c / d;
      DoubleIntToInt  bar = (c,d) => c + d;
       var wrongTypedefReturnType = new FunctionMock<BinaryIntToInt>(foo);
       var wrongTypedefArgumentType = new FunctionMock<BinaryIntToInt>(bar);
       wrongTypedefReturnType(1.1,2.1);
       wrongTypedefArgumentType(1.1,2.1);

    });
    test("Throws with type annotation", () {
      double foo_ (int c, int d)  => c / d;
      BinaryIntToDouble foo = foo_;
      int  bar_ (double c, int d)  => 10;
      DoubleIntToInt  bar = bar_;
      TypeError returnTypeError, argumentTypeError;
      try {
       var wrongTypedefReturnType = new FunctionMock<BinaryIntToInt>(foo);
      }
      catch(exception) {
        expect(exception is TypeError, true);
        returnTypeError = exception;
        }
      try {
       var wrongTypedefArgumentType = new FunctionMock<BinaryIntToInt>(bar);
      }
       catch(exception) {
         expect(exception is TypeError, true);
         argumentTypeError = exception;
         }
      expect(returnTypeError != null,  true);
      expect(argumentTypeError != null,  true);
    });
  }
  );
}

class _Sentinel {
  const _Sentinel();
}
const NO_ARG = const _Sentinel();

class FunctionMock<FunctionTypedef> extends Mock implements Function{

  final  FunctionTypedef _callable;


  FunctionMock._internal(FunctionTypedef function) : _callable = function {
    when(callsTo('call')).alwaysCall(_callable);
   }
  //Place to 'shovel in' black magic if needed.
  factory  FunctionMock(FunctionTypedef function){
    return new FunctionMock._internal(function);
  }

  call([arg0 = NO_ARG,
        arg1 = NO_ARG,
        arg2 = NO_ARG,
        arg3 = NO_ARG,
        arg4 = NO_ARG,
        arg5 = NO_ARG,
        arg6 = NO_ARG,
        arg7 = NO_ARG,
        arg8 = NO_ARG,
        arg9 = NO_ARG]) {
    if (identical(arg0, NO_ARG)) return super.call();
    if (identical(arg1, NO_ARG)) return super.call(arg0);
    if (identical(arg2, NO_ARG)) return super.call(arg0, arg1);
    if (identical(arg3, NO_ARG)) return super.call(arg0, arg1, arg2);
    if (identical(arg4, NO_ARG)) return super.call(arg0, arg1, arg2, arg3);
    if (identical(arg5, NO_ARG)) return super.call(arg0, arg1, arg2, arg3, arg4);
    if (identical(arg6, NO_ARG)) return super.call(arg0, arg1, arg2, arg3, arg4,
        arg5);
    if (identical(arg7, NO_ARG)) return super.call(arg0, arg1, arg2, arg3, arg4,
        arg5, arg6);
    if (identical(arg8, NO_ARG)) return super.call(arg0, arg1, arg2, arg3, arg4,
        arg5, arg6, arg7);
    if (identical(arg9, NO_ARG)) return super.call(arg0, arg1, arg2, arg3, arg4,
        arg5, arg6, arg7, arg8);
    return super.call(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9);
  }
}

*It works for 0-9 arguments - same as callsTo

JAre
  • 4,666
  • 3
  • 27
  • 45