Flutter 中的单元测试通过 BuildContext

Flutter 中的单元测试通过 BuildContext

问题描述:

我在 Dart 类中有一个方法,它接受 BuildContext 参数,如下:

I have a method in a Dart class, which accepts BuildContext parameter, as follows:

class MyClass {

  <return_type> myMethodName(BuildContext context, ...) {
        ...
        doSomething
        return something;
    }
}

我想测试该方法是否按预期工作:

I want to test that the method works as expected:

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
...

void main() {
  MyClass sut;

  setUp(() {
    sut = MyClass();
  });

  test('me testing', () {

    var actual = sut.myMethodName(...);        

    expect(actual, something);
  });
}

当然不行,因为方法myMethodName需要一个参数BuildContext类型.该值在整个应用程序本身中都可用,但不确定在我的单元测试中从何处获取该值.

Of course, it won't work, because the method myMethodName needs a parameter BuildContext type. This value is available throughout the application itself, but not sure where to get that from in my unit tests.

您实际上可以模拟 BuildContext 以便测试将无头运行.我认为它更好,但可能不是您正在寻找的解决方案.

You can actually mock the BuildContext so the test will run headless. I think it's better but might be not a solution that you are looking for.

BuildContext 是一个抽象类,因此它不能被实例化.任何抽象类都可以通过创建该类的实现来模拟.如果我以您的示例为例,则代码将如下所示:

BuildContext is an abstract class therefore it cannot be instantiated. Any abstract class can be mocked by creating implementations of that class. If I take your example then the code will look like this:

class MockBuildContext extends Mock implements BuildContext {}

void main() {
   MyClass sut;
   MockBuildContext _mockContext;

   setUp(() {
     sut = MyClass();
     _mockContext = MockBuildContext();
   });

   test('me testing', () {

   var actual = sut.myMethodName(_mockContext, ...);        

   expect(actual, something);
  });
}