【问题标题】:Chain multiple calls with same arguments to return different results使用相同的参数链接多个调用以返回不同的结果
【发布时间】:2019-05-22 14:25:55
【问题描述】:

我正在编写一个 Flutter 应用程序,该应用程序具有一些广泛的单元测试覆盖率。
我正在使用Mockito 来模拟我的课程。
来自Java (Android) 世界,我可以使用Mockito 链接调用以在后续调用中返回不同的值。
我希望这能奏效。

import 'package:test/test.dart';
import 'package:mockito/mockito.dart';

void main() {
  test("some string test", () {
    StringProvider strProvider = MockStringProvider();
    when(strProvider.randomStr()).thenReturn("hello");
    when(strProvider.randomStr()).thenReturn("world");

    expect(strProvider.randomStr(), "hello");
    expect(strProvider.randomStr(), "world");
  });
}

class StringProvider {
  String randomStr() => "real implementation";
}

class MockStringProvider extends Mock implements StringProvider {}

但是它抛出:

Expected: 'hello'
Actual:   'world'
  Which: is different.

我发现唯一可行的方法是跟踪自己。

void main() {
  test("some string test", () {
    StringProvider strProvider = MockStringProvider();

    var invocations = 0;
    when(strProvider.randomStr()).thenAnswer((_) {
      var a = '';
      if (invocations == 0) {
        a = 'hello';
      } else {
        a = 'world';
      }
      invocations++;
      return a;
    });

    expect(strProvider.randomStr(), "hello");
    expect(strProvider.randomStr(), "world");
  });
}

00:01 +1:所有测试通过!

有没有更好的办法?

【问题讨论】:

    标签: unit-testing dart flutter mockito


    【解决方案1】:

    使用列表并通过removeAt返回答案:

    import 'package:test/test.dart';
    import 'package:mockito/mockito.dart';
    
    void main() {
      test("some string test", () {
        StringProvider strProvider = MockStringProvider();
        var answers = ["hello", "world"];
    
        when(strProvider.randomStr()).thenAnswer((_) => answers.removeAt(0));
    
        expect(strProvider.randomStr(), "hello");
        expect(strProvider.randomStr(), "world");
      });
    }
    
    class StringProvider {
      String randomStr() => "real implementation";
    }
    
    class MockStringProvider extends Mock implements StringProvider {}
    

    【讨论】:

    • 这似乎是一个合理的选择。谢谢
    【解决方案2】:

    您不必在测试开始时调用when

    StringProvider strProvider = MockStringProvider();
    when(strProvider.randomStr()).thenReturn("hello");
    expect(strProvider.randomStr(), "hello");
    
    when(strProvider.randomStr()).thenReturn("world");
    expect(strProvider.randomStr(), "world");
    

    Mockito is dart 有不同的行为。后续调用会覆盖该值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多