Skip to content

test: add unit tests for SyncJobDef and NetworkServiceImpl#1036

Open
andoriyaprashant wants to merge 1 commit into
mosip:masterfrom
andoriyaprashant:syncandnetwork
Open

test: add unit tests for SyncJobDef and NetworkServiceImpl#1036
andoriyaprashant wants to merge 1 commit into
mosip:masterfrom
andoriyaprashant:syncandnetwork

Conversation

@andoriyaprashant
Copy link
Copy Markdown

@andoriyaprashant andoriyaprashant commented May 8, 2026

Fixes #1035

Summary

Added comprehensive unit tests for:

  • SyncJobDef
  • NetworkServiceImpl

Changes Made

SyncJobDef Tests

  • Constructor validation
  • fromJson parsing
  • Null and empty value handling
  • Boolean field validation
  • Edge case coverage
  • Instance integrity checks

NetworkServiceImpl Tests

  • Factory and initialization tests
  • Method availability tests
  • Platform channel mocking
  • Exception handling tests
  • Edge case and stability tests
  • Async call validation

Summary by CodeRabbit

  • Tests
    • Expanded test coverage for network service functionality, including version management and global parameter operations.
    • Added comprehensive test suite for sync job definition handling with edge-case and JSON parsing validation.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 8, 2026

Review Change Stack

Warning

Rate limit exceeded

@andoriyaprashant has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 57 minutes and 43 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: c3a24113-c928-413a-a60a-42cdf746ff16

📥 Commits

Reviewing files that changed from the base of the PR and between 9212c1f and d244bdb.

📒 Files selected for processing (2)
  • test/network_service_impl_test.dart
  • test/sync_job_def_test.dart

Walkthrough

This PR adds two comprehensive unit test suites for the Android Registration Client: NetworkServiceImpl covering platform channel mocking, error handling, and async stability (303 lines), and SyncJobDef covering JSON deserialization, field edge cases, and instance independence (264 lines). Both test files are complete and independent implementations without shared dependencies.

Changes

NetworkServiceImpl Test Suite

Layer / File(s) Summary
Test Infrastructure & Imports
test/network_service_impl_test.dart
Imports testing libraries, defines StandardMessageCodec serialization, and enumerates platform channel names for mocking Pigeon APIs.
Mock Helper Functions
test/network_service_impl_test.dart
Helper functions register successful string responses, error payloads, and clear handlers between test runs.
Test Lifecycle Hooks
test/network_service_impl_test.dart
setUp constructs NetworkServiceImpl and seeds mock responses; tearDown clears all registered handlers.
Factory & Initialization Tests
test/network_service_impl_test.dart
Factory getNetworkServiceImpl() and constructor NetworkServiceImpl() return instances; each call produces distinct objects.
Method Presence & Type Checks
test/network_service_impl_test.dart
checkInternetConnection and getVersionNoApp exist and return Future<String>.
Core Method Functionality
test/network_service_impl_test.dart
saveVersionToGlobalParam, getVersionFromGobalParam, and saveScreenHeaderToGlobalParam return mocked success values for normal and varied inputs.
Error Handling
test/network_service_impl_test.dart
Platform exception mocks confirm saveVersionToGlobalParam, getVersionFromGobalParam, and saveScreenHeaderToGlobalParam return empty strings on failure.
Edge Cases & Stability
test/network_service_impl_test.dart
Repeated saves, special characters, numeric strings, and sequential async calls confirm consistent behavior across invocations.

SyncJobDef Test Suite

Layer / File(s) Summary
Constructor Tests
test/sync_job_def_test.dart
SyncJobDef constructor with all parameters assigns fields correctly; constructor without arguments produces all-null fields.
JSON Deserialization
test/sync_job_def_test.dart
fromJson parses complete JSON, explicit nulls, empty JSON, and ignores unknown keys; known fields populate correctly.
Boolean Field Handling
test/sync_job_def_test.dart
isDeleted and isActive fields parse true and false values correctly from JSON.
String Field Edge Cases
test/sync_job_def_test.dart
String fields retain long strings, special characters, Unicode text, and empty strings without truncation.
Instance Independence & Immutability
test/sync_job_def_test.dart
Multiple constructor instances maintain independent field values; fromJson creates distinct objects from identical JSON.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 New tests hop with glee,
NetworkService flows so free,
SyncJobDef's JSON parsed right,
Edge cases dance in platform light,
Coverage blooms, reliability's bright! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately and concisely describes the main change: adding unit tests for two components (SyncJobDef and NetworkServiceImpl).
Linked Issues check ✅ Passed The pull request fully addresses issue #1035 requirements: comprehensive unit tests for SyncJobDef (constructor, fromJson, null/empty handling, boolean fields, edge cases) and NetworkServiceImpl (factory, initialization, platform channels, exception handling, stability, async calls).
Out of Scope Changes check ✅ Passed All changes are test files directly aligned with issue #1035; no out-of-scope modifications to production code or unrelated areas detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Signed-off-by: andoriyaprashant <prashantandoriya@gmail.com>
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
test/network_service_impl_test.dart (1)

253-269: ⚡ Quick win

These async “logic tests” can pass even when calls fail.

isA<Future<String>>() only checks the returned object type, not completion/result. This does not validate async behavior and can miss runtime channel failures.

Suggested fix
 group('checkInternetConnection Logic Tests', () {
-  test('method returns Future<String> type', () {
-    expect(
-      networkService.checkInternetConnection(),
-      isA<Future<String>>(),
-    );
+  test('method completes with a String', () async {
+    await expectLater(
+      networkService.checkInternetConnection(),
+      completion(isA<String>()),
+    );
   });
 });

 group('getVersionNoApp Logic Tests', () {
-  test('method returns Future<String> type', () {
-    expect(
-      networkService.getVersionNoApp(),
-      isA<Future<String>>(),
-    );
+  test('method completes with a String', () async {
+    await expectLater(
+      networkService.getVersionNoApp(),
+      completion(isA<String>()),
+    );
   });
 });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/network_service_impl_test.dart` around lines 253 - 269, The tests only
assert the returned object type (isA<Future<String>>), which doesn't verify the
Future completes or yields a valid value; change the tests for
checkInternetConnection and getVersionNoApp to actually await or assert
completion and result type—use expect(networkService.checkInternetConnection(),
completion(isA<String>())) or expect(networkService.checkInternetConnection(),
completes) and then await the call and assert the returned String; do the same
for getVersionNoApp to ensure channel/platform errors surface rather than just
type-checking the Future.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/network_service_impl_test.dart`:
- Around line 208-218: The test is injecting platform errors into the wrong
channel (mockPlatformError(saveVersionChannels)) so the
saveScreenHeaderToGlobalParam error path isn't exercised; update the test to
call mockPlatformError with the screen-header method channel (e.g.,
saveScreenHeaderChannels or the exact channel constant used by
networkService.saveScreenHeaderToGlobalParam) instead of saveVersionChannels so
the platform exception is routed to networkService.saveScreenHeaderToGlobalParam
during the test.

In `@test/sync_job_def_test.dart`:
- Around line 135-167: Add tests under the existing "Boolean Field Tests" group
that pass malformed boolean values into SyncJobDef.fromJson (e.g., {'isDeleted':
'true'}, {'isDeleted': 1}, {'isActive': 'false'}, {'isActive': 0}) and assert
the parser rejects them by expecting a thrown error (use expect(...,
throwsA(...))) to lock the parsing contract; reference SyncJobDef.fromJson and
the isDeleted/isActive fields so the tests fail if the deserializer silently
accepts non-boolean types.

---

Nitpick comments:
In `@test/network_service_impl_test.dart`:
- Around line 253-269: The tests only assert the returned object type
(isA<Future<String>>), which doesn't verify the Future completes or yields a
valid value; change the tests for checkInternetConnection and getVersionNoApp to
actually await or assert completion and result type—use
expect(networkService.checkInternetConnection(), completion(isA<String>())) or
expect(networkService.checkInternetConnection(), completes) and then await the
call and assert the returned String; do the same for getVersionNoApp to ensure
channel/platform errors surface rather than just type-checking the Future.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a7e39192-6ecf-4e11-a39c-f3864e971b01

📥 Commits

Reviewing files that changed from the base of the PR and between aef4fb6 and 9212c1f.

📒 Files selected for processing (2)
  • test/network_service_impl_test.dart
  • test/sync_job_def_test.dart

Comment on lines +208 to +218
test('saveScreenHeaderToGlobalParam returns empty string on platform error',
() async {
mockPlatformError(saveVersionChannels);

final response = await networkService.saveScreenHeaderToGlobalParam(
'header',
'value',
);

expect(response, '');
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Mocked error channel is likely wrong for saveScreenHeaderToGlobalParam.

Line 210 injects platform errors into saveVersionChannels, not the screen-header method channel. This can make the test pass without exercising the intended error path.

Suggested fix
+  const List<String> saveScreenHeaderChannels = <String>[
+    'dev.flutter.pigeon.registration_client.CommonDetailsApi.saveScreenHeaderToGlobalParam',
+    'dev.flutter.pigeon.registration_client.pigeon.CommonDetailsApi.saveScreenHeaderToGlobalParam',
+  ];
+
   void clearMockHandlers() {
     for (final channel in <String>[
       ...saveVersionChannels,
       ...getVersionChannels,
+      ...saveScreenHeaderChannels,
     ]) {
       TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
           .setMockMessageHandler(channel, null);
     }
   }

   setUp(() {
     networkService = NetworkServiceImpl();

     mockStringResponse(saveVersionChannels, 'saved_successfully');
     mockStringResponse(getVersionChannels, '1.0.0');
+    mockStringResponse(saveScreenHeaderChannels, 'saved_successfully');
   });

   test('saveScreenHeaderToGlobalParam returns empty string on platform error',
       () async {
-    mockPlatformError(saveVersionChannels);
+    mockPlatformError(saveScreenHeaderChannels);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test('saveScreenHeaderToGlobalParam returns empty string on platform error',
() async {
mockPlatformError(saveVersionChannels);
final response = await networkService.saveScreenHeaderToGlobalParam(
'header',
'value',
);
expect(response, '');
});
const List<String> saveScreenHeaderChannels = <String>[
'dev.flutter.pigeon.registration_client.CommonDetailsApi.saveScreenHeaderToGlobalParam',
'dev.flutter.pigeon.registration_client.pigeon.CommonDetailsApi.saveScreenHeaderToGlobalParam',
];
void clearMockHandlers() {
for (final channel in <String>[
...saveVersionChannels,
...getVersionChannels,
...saveScreenHeaderChannels,
]) {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMessageHandler(channel, null);
}
}
setUp(() {
networkService = NetworkServiceImpl();
mockStringResponse(saveVersionChannels, 'saved_successfully');
mockStringResponse(getVersionChannels, '1.0.0');
mockStringResponse(saveScreenHeaderChannels, 'saved_successfully');
});
test('saveScreenHeaderToGlobalParam returns empty string on platform error',
() async {
mockPlatformError(saveScreenHeaderChannels);
final response = await networkService.saveScreenHeaderToGlobalParam(
'header',
'value',
);
expect(response, '');
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/network_service_impl_test.dart` around lines 208 - 218, The test is
injecting platform errors into the wrong channel
(mockPlatformError(saveVersionChannels)) so the saveScreenHeaderToGlobalParam
error path isn't exercised; update the test to call mockPlatformError with the
screen-header method channel (e.g., saveScreenHeaderChannels or the exact
channel constant used by networkService.saveScreenHeaderToGlobalParam) instead
of saveVersionChannels so the platform exception is routed to
networkService.saveScreenHeaderToGlobalParam during the test.

Comment on lines +135 to +167
group('Boolean Field Tests', () {
test('isDeleted supports true value', () {
final syncJobDef = SyncJobDef.fromJson({
'isDeleted': true,
});

expect(syncJobDef.isDeleted, true);
});

test('isDeleted supports false value', () {
final syncJobDef = SyncJobDef.fromJson({
'isDeleted': false,
});

expect(syncJobDef.isDeleted, false);
});

test('isActive supports true value', () {
final syncJobDef = SyncJobDef.fromJson({
'isActive': true,
});

expect(syncJobDef.isActive, true);
});

test('isActive supports false value', () {
final syncJobDef = SyncJobDef.fromJson({
'isActive': false,
});

expect(syncJobDef.isActive, false);
});
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add invalid-type boolean tests to lock parser contract.

You validate true/false, but not malformed inputs (e.g., 'true', 1). Adding these catches type-safety regressions in fromJson.

Suggested test additions
   group('Boolean Field Tests', () {
@@
     test('isActive supports false value', () {
       final syncJobDef = SyncJobDef.fromJson({
         'isActive': false,
       });

       expect(syncJobDef.isActive, false);
     });
+
+    test('isDeleted rejects non-boolean values', () {
+      expect(
+        () => SyncJobDef.fromJson({'isDeleted': 'true'}),
+        throwsA(isA<TypeError>()),
+      );
+    });
+
+    test('isActive rejects non-boolean values', () {
+      expect(
+        () => SyncJobDef.fromJson({'isActive': 1}),
+        throwsA(isA<TypeError>()),
+      );
+    });
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/sync_job_def_test.dart` around lines 135 - 167, Add tests under the
existing "Boolean Field Tests" group that pass malformed boolean values into
SyncJobDef.fromJson (e.g., {'isDeleted': 'true'}, {'isDeleted': 1}, {'isActive':
'false'}, {'isActive': 0}) and assert the parser rejects them by expecting a
thrown error (use expect(..., throwsA(...))) to lock the parsing contract;
reference SyncJobDef.fromJson and the isDeleted/isActive fields so the tests
fail if the deserializer silently accepts non-boolean types.

@andoriyaprashant
Copy link
Copy Markdown
Author

Hi @SachinPremkumar @Pragya279 could you please review this Pull request and let me know if any changes are needed
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add unit tests for SyncJobDef and NetworkServiceImpl

1 participant