【问题标题】:How can I mock the indexing operator with dart mockito?如何使用 dart mockito 模拟索引运算符?
【发布时间】:2015-09-18 21:52:30
【问题描述】:

我正在编写一个单元测试,我需要在其中模拟一个 JsObject,这样我就不需要在我的测试中进行实际的 javascript 互操作。但是,我使用索引运算符[] 来访问我的JsObject 中的一个字段。我正在使用 dart mockito 库 https://github.com/fibulwinter/dart-mockito 进行模拟,但我似乎无法找到如何模拟操作符在被模拟对象上的行为。

【问题讨论】:

    标签: unit-testing dart operators mockito


    【解决方案1】:

    Mockito 使存根变得非常容易,对索引运算符进行存根就像对任何其他方法进行存根一样。想象你想要存根以下类的索引运算符:

    class IndexTest {
      operator[] (String value);
    }
    

    在第一步中,我们为该类创建一个模拟:

    class MockIndexTest extends Mock implements IndexTest {
      noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
    }
    

    现在在您的测试中,您可以使用索引运算符设置您期望的调用返回值:

      test('Test', () {
        final t = new MockIndexTest();
    
        // Set return values
        when(t[any]).thenReturn(0); // 1
        when(t['one']).thenReturn(1); // 2
        when(t['two']).thenReturn(2); // 3
    
        // Check return values
        expect(t['one'], equals(1));
        expect(t['two'], equals(2));
        expect(t['something else'], equals(0));
      });
    

    不存根调用总是返回null。使用 mockito 提供的 any 值,您可以为带有任何参数的调用设置默认返回值(参见 1)。您还可以为一组特定的参数设置返回值(参见 2 和 3)。您必须在设置特定值之前设置默认值。

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 2016-05-08
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多