How to test and to what extend should I write unit tests?

I am new to unit testing, and currently working on a new release of one of my packages to be testable.

Currently, I am struggling to see when and what to test. Take the following script for reference:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class AuthService {
AuthService({
required this.client,
});
final SimpleGraphQl client;
Future<LoginResponseDto> login({
required String username,
required String password,
}) async {
const query = r'''
query Login($username: String, $password, String) {
login(username: $username, password: $password) {
success
token
}
}''';
final variables = {'username': username, 'password': password};
final response = await client.query<LoginResponseDto>(
variables: variables,
query: query,
resultBuilder: (data) {
return LoginResponseDto.fromJson(
data['login'] as Map<String, dynamic>,
);
});
return response;
}
}
</code>
<code>class AuthService { AuthService({ required this.client, }); final SimpleGraphQl client; Future<LoginResponseDto> login({ required String username, required String password, }) async { const query = r''' query Login($username: String, $password, String) { login(username: $username, password: $password) { success token } }'''; final variables = {'username': username, 'password': password}; final response = await client.query<LoginResponseDto>( variables: variables, query: query, resultBuilder: (data) { return LoginResponseDto.fromJson( data['login'] as Map<String, dynamic>, ); }); return response; } } </code>
class AuthService {
  AuthService({
    required this.client,
  });

  final SimpleGraphQl client;

  Future<LoginResponseDto> login({
    required String username,
    required String password,
  }) async {
    const query = r'''
      query Login($username: String, $password, String) { 
        login(username: $username, password: $password) {
          success
          token
        }
      }''';

    final variables = {'username': username, 'password': password};

    final response = await client.query<LoginResponseDto>(
        variables: variables,
        query: query,
        resultBuilder: (data) {
          return LoginResponseDto.fromJson(
            data['login'] as Map<String, dynamic>,
          );
        });

    return response;
  }
}
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class LoginResponseDto {
LoginResponseDto({
required this.success,
required this.token,
});
final bool success;
final String? token;
factory LoginResponseDto.fromJson(Map<String, dynamic> json) {
return LoginResponseDto(
success: json['success'] as bool,
token: json['token'] as String?,
);
}
}
</code>
<code>class LoginResponseDto { LoginResponseDto({ required this.success, required this.token, }); final bool success; final String? token; factory LoginResponseDto.fromJson(Map<String, dynamic> json) { return LoginResponseDto( success: json['success'] as bool, token: json['token'] as String?, ); } } </code>
class LoginResponseDto {
  LoginResponseDto({
    required this.success,
    required this.token,
  });

  final bool success;
  final String? token;

  factory LoginResponseDto.fromJson(Map<String, dynamic> json) {
    return LoginResponseDto(
      success: json['success'] as bool,
      token: json['token'] as String?,
    );
  }
}

This service handles authentication logic using a GraphQL wrapper called SimpleGraphQl, which takes the GraphQL query, variables, and a callback for response serialization. The service examples include just the login method.

When deciding which case scenarios I should test, I decided to test:

  1. Client query variables parameter must include username and password keys.
  2. Test success and failure login attempts (e.g. when success in response is either true or false).

So, I wrote the following tests:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>void main() {
group('AuthService', () {
late SimpleGraphQlMock client;
setUp(() {
client = SimpleGraphQlMock();
});
test('login mutation includes "username" and "password" variables',
() async {
final service = AuthService(client: client);
when(
() => client.query<LoginResponseDto>(
query: any(named: 'query'),
variables: any(named: 'variables'),
resultBuilder: any(named: 'resultBuilder'),
),
).thenAnswer(
(_) async => LoginResponseDto.fromJson(
{'success': true, 'token': 'test_eyJhb....sw5c'},
),
);
await service.login(username: 'john_doe', password: '12345');
final captured = verify(
() => client.query<LoginResponseDto>(
query: any(named: 'query'),
variables: captureAny(named: 'variables'),
resultBuilder: any(named: 'resultBuilder'),
),
).captured;
/// Login mutation includes username and password variables.
expect(captured[0].containsKey('username'), true);
expect(captured[0].containsKey('password'), true);
});
test('should login successfully using correct credentials', () async {
final service = AuthService(client: client);
when(
() => client.query<LoginResponseDto>(
query: any(named: 'query'),
variables: any(named: 'variables'),
resultBuilder: any(named: 'resultBuilder'),
),
).thenAnswer(
(_) async => LoginResponseDto.fromJson(
{'success': true, 'token': 'test_eyJhb....sw5c'},
),
);
final response = await service.login(
username: 'john_doe',
password: '12345',
);
expect(response.success, true);
expect(response.token, 'test_eyJhb....sw5c');
});
test('login should fail when incorrect credentials are sent', () async {
final service = AuthService(client: client);
when(
() => client.query<LoginResponseDto>(
query: any(named: 'query'),
variables: any(named: 'variables'),
resultBuilder: any(named: 'resultBuilder'),
),
).thenAnswer(
(_) async => LoginResponseDto.fromJson(
{'success': false, 'token': null},
),
);
final response = await service.login(
username: 'john_doe',
password: 'wrong password',
);
expect(response.success, false);
expect(response.token, null);
});
});
}
</code>
<code>void main() { group('AuthService', () { late SimpleGraphQlMock client; setUp(() { client = SimpleGraphQlMock(); }); test('login mutation includes "username" and "password" variables', () async { final service = AuthService(client: client); when( () => client.query<LoginResponseDto>( query: any(named: 'query'), variables: any(named: 'variables'), resultBuilder: any(named: 'resultBuilder'), ), ).thenAnswer( (_) async => LoginResponseDto.fromJson( {'success': true, 'token': 'test_eyJhb....sw5c'}, ), ); await service.login(username: 'john_doe', password: '12345'); final captured = verify( () => client.query<LoginResponseDto>( query: any(named: 'query'), variables: captureAny(named: 'variables'), resultBuilder: any(named: 'resultBuilder'), ), ).captured; /// Login mutation includes username and password variables. expect(captured[0].containsKey('username'), true); expect(captured[0].containsKey('password'), true); }); test('should login successfully using correct credentials', () async { final service = AuthService(client: client); when( () => client.query<LoginResponseDto>( query: any(named: 'query'), variables: any(named: 'variables'), resultBuilder: any(named: 'resultBuilder'), ), ).thenAnswer( (_) async => LoginResponseDto.fromJson( {'success': true, 'token': 'test_eyJhb....sw5c'}, ), ); final response = await service.login( username: 'john_doe', password: '12345', ); expect(response.success, true); expect(response.token, 'test_eyJhb....sw5c'); }); test('login should fail when incorrect credentials are sent', () async { final service = AuthService(client: client); when( () => client.query<LoginResponseDto>( query: any(named: 'query'), variables: any(named: 'variables'), resultBuilder: any(named: 'resultBuilder'), ), ).thenAnswer( (_) async => LoginResponseDto.fromJson( {'success': false, 'token': null}, ), ); final response = await service.login( username: 'john_doe', password: 'wrong password', ); expect(response.success, false); expect(response.token, null); }); }); } </code>
void main() {
  group('AuthService', () {
    late SimpleGraphQlMock client;

    setUp(() {
      client = SimpleGraphQlMock();
    });

    test('login mutation includes "username" and "password" variables',
        () async {
      final service = AuthService(client: client);

      when(
        () => client.query<LoginResponseDto>(
          query: any(named: 'query'),
          variables: any(named: 'variables'),
          resultBuilder: any(named: 'resultBuilder'),
        ),
      ).thenAnswer(
        (_) async => LoginResponseDto.fromJson(
          {'success': true, 'token': 'test_eyJhb....sw5c'},
        ),
      );

      await service.login(username: 'john_doe', password: '12345');

      final captured = verify(
        () => client.query<LoginResponseDto>(
          query: any(named: 'query'),
          variables: captureAny(named: 'variables'),
          resultBuilder: any(named: 'resultBuilder'),
        ),
      ).captured;

      /// Login mutation includes username and password variables.
      expect(captured[0].containsKey('username'), true);
      expect(captured[0].containsKey('password'), true);
    });

    test('should login successfully using correct credentials', () async {
      final service = AuthService(client: client);

      when(
        () => client.query<LoginResponseDto>(
          query: any(named: 'query'),
          variables: any(named: 'variables'),
          resultBuilder: any(named: 'resultBuilder'),
        ),
      ).thenAnswer(
        (_) async => LoginResponseDto.fromJson(
          {'success': true, 'token': 'test_eyJhb....sw5c'},
        ),
      );

      final response = await service.login(
        username: 'john_doe',
        password: '12345',
      );

      expect(response.success, true);
      expect(response.token, 'test_eyJhb....sw5c');
    });

    test('login should fail when incorrect credentials are sent', () async {
      final service = AuthService(client: client);

      when(
        () => client.query<LoginResponseDto>(
          query: any(named: 'query'),
          variables: any(named: 'variables'),
          resultBuilder: any(named: 'resultBuilder'),
        ),
      ).thenAnswer(
        (_) async => LoginResponseDto.fromJson(
          {'success': false, 'token': null},
        ),
      );

      final response = await service.login(
        username: 'john_doe',
        password: 'wrong password',
      );

      expect(response.success, false);
      expect(response.token, null);
    });
  });
}

Note: I’m using the mocktail library.

However, my concern is that I don’t see value in the second scenario about testing successful and failed login attempts because I’m just forcing a returned object rather than testing the JSON response (which, as far as I know, is a responsibility of the package and not my app). I would see value on this test if this was a dynamically typed language like TypeScript and wanted to ensure that login always returns the correct object. Still, Dart’s type system makes it irrelevant. Is that test relevant, or should I take another approach to it?

In conclusion, I would like to know if the test scenarios I posed are relevant and sufficient and if the test code is correct according to the login use case.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật