簡體   English   中英

為 http.post 創建單元測試的問題

[英]Problems to create a unit test for http.post

我創建了這個 class 以在 dart 中使用 http.post:

class SigninDataSource {
  final http.Client client;

  SigninDataSource(this.client);

  Future<SignIn> signIn ({
    String email = 'test@hotmail.com',
    String password = 'test',
  }) async {
    var url = "https://test/test/signin";
    var body = json.decode('{"email": "$email", "password": "$password"}');

    final result = await client.post(url, body: json.encode(body), headers: {"content-type": "application/json",});
    print("Result");
    print(result);

    if(result.statusCode == 200) {
      SignIn.fromJson((result.body));
      return SignIn.fromJson(result.body);
    } else {
      throw SignInError(json.decode(result.body)['message']);
    }
  }
}

我試圖為它創建一個單元測試。

class MockClient extends Mock implements http.Client {}

void main() {
  String fixture(String name) => File('test/data/fixtures/$name.json').readAsStringSync();

  MockClient mockClient;
  SigninDataSource dataResource;

  setUp((){
    mockClient = MockClient();
    dataResource = SigninDataSource(mockClient);
  });

  group('signin', () {
    test(
      'return SignIn whrn the service call complete succesfully',
        () async {
          when(
            mockClient.post(
              "https://test/test/signin",
              body: '{"email": "test@test.com", "password": "Test@123"}',
              headers: {"content-type": "application/json"}
            )).thenAnswer(
              (_) async => http.Response('{"status": 200}', 200));
          expect(await dataResource.signIn(email: 'test@test.com', password:'Test@123'),TypeMatcher<SignIn>());
        }
    );
  });
}

但我收到此錯誤:

Result
null

NoSuchMethodError: The getter 'statusCode' was called on null.
Receiver: null
Tried calling: statusCode

我認為我的模擬方法不起作用,但我無法弄清楚問題所在。 我正在檢查此文檔https://flutter.dev/docs/cookbook/testing/unit/mocking我試圖為 http.post 復制它。請有更多經驗的人幫我找出問題嗎?

存根期間 mockClient.post() 中的body參數{"email": "test@test.com", "password": "Test@123"}mockClient.post()client.post()中傳遞的SigninDataSource不匹配。

如果您檢查在client.post()中傳遞的字符串

final result = await client.post(url, body: json.encode(body), headers: {
  "content-type": "application/json",
});

var encodedBody = json.encode(body);

final result = await client.post(url, body: encodedBody, headers: {
    "content-type": "application/json",
});

encodedBody的值為{"email":"test@test.com","password":"Test@123"} 注意沒有空格。

如果您想忽略傳遞的參數的值,您也可以修改您的存根,因為您只需要成功響應。 您將使用anyNamed('paramName')

when(mockClient.post("https://test/test/signin",
        body: anyNamed('body'),
        headers: anyNamed('headers')))
    .thenAnswer((_) async => http.Response('{"status": 200}', 200));

暫無
暫無

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

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