Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stubbing/Mocking/Spying a function within a function in dart

Tags:

dart

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:

Main Class:

class ToBeTested {
       int sum(int i, int z) {
                 return addOne(i) + z;
            }
            int addOne(int i) {
                 return i + 1;
            }
     }

Test Created:

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?

like image 836
Anisha Gupta Avatar asked Oct 16 '25 11:10

Anisha Gupta


1 Answers

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);
  });
}
like image 102
Nico Avatar answered Oct 19 '25 14:10

Nico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!