I have been working with Dart for the past couple of days for some unit tests. I have been seeing weird functionality on testing a function within a function where I would mock one function to return something but it does not change the prior function. Code and output displayed below:
class ToBeTested {
       int sum(int i, int z) {
                 return addOne(i) + z;
            }
            int addOne(int i) {
                 return i + 1;
            }
     }
test("hello", () async{
         var ToBeTestedSpy = spy(new ToBeTested(), new ToBeTested(param1,param 2));
         print(ToBeTestedSpy.sum(5, 10));
         when(ToBeTestedSpy.addOne(5)).thenReturn(100);
         print(ToBeTestedSpy.sum(5, 10));
  });
Output: 16 16
Why is the output not 16 110 even after stubbing the spy to override its return to 100?
Spy is deprecated in mockito. Instead it is recommended to handcode part of your stub (or use code generation technique) (see https://github.com/dart-lang/mockito/commit/dc8ce18d6e1096d2546d1ef5afe417cd9e042aee)
I'm not sure of what you want to do but this is what I came up with:
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
abstract class CalcInterface {
  int sum(int i, int z);
  int addOne(int i);
}
abstract class BaseCalc implements CalcInterface {
  int sum(int i, int z) {
    return addOne(i) + z;
  }
}
class Calc extends Object with BaseCalc implements CalcInterface {
  int sum(int i, int z) {
    return addOne(i) + z;
  }
  int addOne(int i) {
    return i + 1;
  }
}
class MockCalc extends Mock with BaseCalc implements CalcInterface {}
main() {
  test("hello", () {
    var mocked = new MockCalc();
    when(mocked.addOne(5)).thenReturn(100);
    expect(mocked.sum(5, 10), 110);
    verify(mocked.addOne(5)).called(1);
  });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With