代码之家  ›  专栏  ›  技术社区  ›  timr

使用相同的参数链接多个调用以返回不同的结果

  •  0
  • timr  · 技术社区  · 7 年前

    我正在写一篇文章 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:所有测试均通过!

    有更好的办法吗?

    2 回复  |  直到 7 年前
        1
  •  11
  •   attdona    7 年前

    使用列表并返回答案 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
  •  4
  •   Rémi Rousselet    7 年前

    你不必打电话 when 在测试开始时:

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

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