如何在 Dart/Flutter 中模拟正在测试的同一类中的方法?

问题描述 投票:0回答:1

在下面的代码中,我想为

a
编写一个单元测试,并且我想模拟
b
。 我如何使用
mockito
或任何其他库来模拟它?

class Test {
  Future<void> a() async {
    await b();
  }

  Future<void> b() async {
    // code
  }
}
flutter dart unit-testing mocking
1个回答
0
投票

您可以执行以下操作:

首先添加mockito:

dev_dependencies:
  mockito: ^5.0.0

您可以尝试如下所示:

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

class MockTest extends Mock implements Test {}

class Test {
  Future<void> a() async {
    await b();
  }

  Future<void> b() async {
 
  }
}

void main() {
  test('Test method a', () async {
    
    final mockTest = MockTest(); // Create an instance of the class, and mock the b method
    when(mockTest.b()).thenAnswer((_) async {
      print('Mocked implementation of b');
    });           
    await mockTest.a(); // Call the method you want to test            
    verify(mockTest.b()).called(1); // Verify that the mocked method was called
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.