簡體   English   中英

有沒有辦法使用Mockito將復雜的參數傳遞給Mocked Dart Services?

[英]Is there a way to pass in complex arguments into Mocked Dart Services using Mockito?

我正在查看文檔: https//pub.dartlang.org/packages/mockito ,並試圖更多地了解它。 似乎在示例中,函數存根接受字符串,但是對於我將如何實現我的Mocked服務感到困惑。

我很好奇我會怎么做。 我所擁有的服務非常簡單直接。

class Group{}
class GroupService {}
class MockGroupService extends Mock implements GroupService {}
final mockProviders = [new Provider(MockGroupService, useExisting: GroupService];

所以你可以看到我正在使用Angular dart。

我在Test文件中創建了一個示例組。

group("service tests", (){
  MockGroupService _mock;
  testBed.addProviders([mockProviders]);

  setUp(() async {
    fixture = await testBed.create();
    _mock = new MockGroupService();

    //This is where I was going to create some stubbs for the methods
    when(_mock.add()).thenReturn((){
      return null; //return the object.
    });

    //create additional when statements for edit, delete, etc.
  });
});

所以我在想的是會有一個參數傳遞給add(或2)....我將如何在when語句中正確編碼,以及這兩個參數如何反映在then語句中?

基本上,我想用復雜的類進行測試..並將其傳遞給add。 然后它會相應地處理它並返回它。

我是否會將參數傳遞給類似於:(使用偽代碼)

when(_mock.add(argThat(hasType(Group)))).thenReturn((Group arg)=> arg);

或類似的東西? hasType isnt函數,所以我不是100%肯定如何處理這個設計。 理想情況下,我嘗試在測試中創建組,然后相應地將其傳遞給add函數。 似乎這些例子顯示了Strings。

是的mockito允許傳遞對象,您可以在測試中看到示例。

這有點難以理解但是你可以在這里看到它使用深度相等來檢查如果沒有指定匹配器,參數是否相等。

你問題的第二部分有點復雜。 如果您想使用傳遞給模擬的值作為響應的一部分,那么您需要使用thenAnswer。 它為您提供了對所調用內容的調用。 從該對象,您可以獲取並返回方法調用中使用的任何參數。

因此,對於您的添加示例,如果您知道傳入的內容並完全訪問它,我會寫:

Group a = new Group();
when(_mock.add(a)).thenReturn(a);

如果Group對象是由其他東西創建的,我會寫:

when(_mock.add(argThat(new isInstanceOf<Group>()))
  .thenAnswer((invocation)=>invocation.positionalArguments[0]);

或者,如果您真的不關心檢查類型。 根據您用於測試的檢查,可能已經為您檢查了類型。

when(_mock.add(any)).thenAnswer(
  (invocation)=>invocation.positionalArguments[0]);

或者如果您使用的是Dart 2.0:

when(_mock.add(typed(any))).thenAnswer(
  (invocation)=>invocation.positionalArguments[0]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM