Skip to content

Added test cases for the coverage [MOSIP-25973]#761

Open
GOKULRAJ136 wants to merge 4 commits intomosip:developfrom
GOKULRAJ136:junit-dev
Open

Added test cases for the coverage [MOSIP-25973]#761
GOKULRAJ136 wants to merge 4 commits intomosip:developfrom
GOKULRAJ136:junit-dev

Conversation

@GOKULRAJ136
Copy link

@GOKULRAJ136 GOKULRAJ136 commented Feb 4, 2026

Summary by CodeRabbit

  • Tests
    • Added extensive unit tests for device specifications, provider implementations, discovery/availability and versioning logic across modalities.
    • Expanded coverage for software update utilities and update handler error paths.
    • Added REST client and response-signature validation tests, including file-download, resume and signature handling scenarios.
    • Added tests for system/property utilities, JSON/date mapping, and numerous edge/error cases across registration services.

Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
@coderabbitai
Copy link

coderabbitai bot commented Feb 4, 2026

Warning

Rate limit exceeded

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

⌛ 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.

Walkthrough

Adds and expands numerous unit tests across registration-services: new tests for device specification factories/providers, SBI provider, software update utilities/handler, registration utility mappers, response signature advice, and REST client utilities, exercising private methods, error paths, versioning, streaming, file-download/resume, and signature-validation scenarios.

Changes

Cohort / File(s) Summary
Device Spec Factory & Provider Tests
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java, registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_092_ProviderImplTest.java, registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_095_ProviderImplTest.java
Adds tests for device lookup/error paths, registry updates, reflection-based verification of private methods (device type/subtype/version), spec parsing, streaming and RCapture flows, device availability, modality/sub-id and default-count logic.
SBI Provider Tests
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java
Significantly expands SBI 1.0 provider tests with PowerMockito/Whitebox usage, mocked ObjectMapper flows, digital ID decoding, device retrieval/streaming/RCapture scenarios, and many private/internal logic paths.
Software Update Tests
registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateHandlerTest.java, registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateUtilTest.java
Adds a handler test for manifest/version-mapping error handling and a new SoftwareUpdateUtilTest covering JAR checksum validation, download/delete flows, temp dir management, and related edge/error cases.
Registration / Mapper Utilities
registration/registration-services/src/test/java/io/mosip/registration/test/util/RegistrationSystemPropertiesCheckerTest.java, registration/registration-services/src/test/java/io/mosip/registration/test/util/mastersync/MapperTest.java
Adds a real-call machine-id test and expands MapperUtils tests (via reflection) for LocalDate/LocalDateTime parsing and JSON (de)serialization error/success cases.
Response Signature Tests
registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/ResponseSignatureAdviceTest.java
Extends signature validation tests to cover null signRequired, missing/malformed headers, missing response-body maps, use of new public key from response, and file-based signature validation paths; adds TemporaryFolder-based file utilities and multiple mocks.
Rest Client Tests
registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/RestClientUtilTest.java
Adds RestClientUtilTest covering URL/token invocation mappings, connectivity health checks, file download with resume and signature persistence, and HTTP request factory timeout behavior; uses PowerMockito/Mockito and FileSignatureRepository mocks.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 I hopped through tests both wide and deep,
Mocked, spied, and peeked where secrets sleep,
Versions, devices, downloads too—
I stitched assertions, one by two,
Carrots, coverage, a tidy leap.

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.71% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the pull request's primary purpose: adding multiple comprehensive test cases across the registration service module to improve code coverage.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

Copy link

@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: 11

🤖 Fix all issues with AI agents
In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_092_ProviderImplTest.java`:
- Around line 163-188: The test should capture and assert the boolean returned
by provider.isDeviceAvailable so it actually verifies expected behavior; update
the test method shouldReturnTrueWhenDeviceAvailableMatches to store the result
(e.g., boolean available = provider.isDeviceAvailable(dev)) and add an assertion
that available is true (use the test framework's assertTrue/assertThat) while
keeping existing Mockito stubs for helper.getMapper, helper.buildUrl, and
helper.getHttpClientResponseEntity.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_095_ProviderImplTest.java`:
- Around line 13-17: The test class
MosipDeviceSpecification_095_ProviderImplTest uses `@InjectMocks` on the field
mockObject (MosipDeviceSpecification_095_ProviderImpl) but never initializes
Mockito; add MockitoAnnotations.openMocks(this) in a `@Before` method to
initialize `@InjectMocks` (or remove `@InjectMocks` and instantiate mockObject with
new MosipDeviceSpecification_095_ProviderImpl() if there are no injected mocks)
so the mock injection actually occurs.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java`:
- Around line 169-183: The test is only validating pre-built lists because it
uses a full mock (mockedObject) instead of invoking the real implementation;
replace the full mock with the `@InjectMocks` instance (mockObject /
MosipDeviceSpecification_SBI_1_0_ProviderImpl) so only dependencies (e.g.,
mosipDeviceSpecificationHelper, mapper) are mocked, configure those dependency
stubs (getMapper, getDeviceInfoDecoded, etc.), call
mockObject.getMdmDevices(inputDeviceInfo, port) to obtain the real result, and
assert that result matches the expected excpectedMdmBioDevices; remove the
when(mockedObject.getMdmDevices(...)) stub and ensure actualBioDevice setup and
port injection remain identical before assertion.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java`:
- Around line 84-98: The helper invokePrivate currently calls
ReflectionUtils.findMethod without checking its return, which can cause a null
pointer; modify invokePrivate (the method that builds paramTypes, calls
ReflectionUtils.findMethod, ReflectionUtils.makeAccessible and
ReflectionUtils.invokeMethod) to check if the returned Method is null and throw
a clear exception (e.g., IllegalStateException) that includes the
target.getClass().getName(), methodName and the parameter type list, and only
call ReflectionUtils.makeAccessible/invokeMethod when Method is non-null so
failures produce a descriptive error instead of a NullPointerException.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateUtilTest.java`:
- Around line 16-23: Remove the unused `@InjectMocks` field and stop calling
static utility methods on an uninitialized instance: delete the private
SoftwareUpdateUtil softwareUpdateUtil field (and its `@InjectMocks` annotation) in
SoftwareUpdateUtilTest, then update all calls like
softwareUpdateUtil.deleteUnknownJars(...) to call the static methods directly
via the class or inherited context (SoftwareUpdateUtil.deleteUnknownJars(...) or
this.deleteUnknownJars(...)); alternatively, if you intended to use Mockito
injection, initialize mocks in a `@Before` method with
MockitoAnnotations.openMocks(this) and keep the field, but prefer removing the
field since SoftwareUpdateUtil only exposes protected static methods.
- Around line 37-44: The cleanup helper deleteDir(File dir) can throw a
NullPointerException when dir.listFiles() returns null; update the
deleteDir(File dir) method to check that dir.listFiles() != null (or that
dir.isDirectory()) before iterating over files and attempting f.delete(), and
only call dir.delete() afterwards — specifically modify the deleteDir(File dir)
implementation to guard the for-loop with a null check on dir.listFiles().

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/util/mastersync/MapperTest.java`:
- Around line 229-234: The test testGetLocalDateTimeValue_nullInput currently
has an unreachable assertion because it declares expected = NullPointerException
while also asserting result is null; locate the test method
testGetLocalDateTimeValue_nullInput and either remove the expected =
NullPointerException clause if the intended behavior is to return null (keep the
assertNull(result) and verify invokeMethod(null) returns null), or remove the
assertNull(result) and keep expected = NullPointerException if the intended
behavior is to throw; update the test accordingly to only assert one expected
outcome for invokeMethod.
- Around line 277-282: The test testGetLocalDateValue_nullInput declares
expected=NullPointerException but then asserts the result is null, making
assertNull unreachable; update the test to match intent by removing the
expected=NullPointerException from the `@Test` annotation so
invokeGetLocalDateValue(null) returns and the assertNull(result) executes, or
alternatively remove the assertNull if the intended behavior is to expect an
exception; locate testGetLocalDateValue_nullInput and adjust the `@Test`
annotation or assertion accordingly to make the test reachable and consistent
with invokeGetLocalDateValue.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/util/RegistrationSystemPropertiesCheckerTest.java`:
- Around line 24-30: The test getMachineId_success_realCall in
RegistrationSystemPropertiesCheckerTest is flaky because it relies on
InetAddress.getLocalHost(); remove or replace this real-host lookup test and
either consolidate it with the existing testGetMachineId() or make it
deterministic by mocking InetAddress.getLocalHost() (or refactor
RegistrationSystemPropertiesChecker to accept a HostProvider and inject a test
implementation); update assertions to use the mocked/provider result and ensure
all references to getMachineId() in tests use the deterministic provider or
consolidated test.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/ResponseSignatureAdviceTest.java`:
- Around line 372-388: The test method
shouldSkipValidationWhenSignRequiredIsNull in ResponseSignatureAdviceTest
declares an expected RegBaseCheckedException but then calls
Mockito.verify(signatureService, Mockito.never()).jwtVerify(...) after the call
to responseSignatureAdvice.responseSignatureValidation(joinPointMock,
linkedMap), which is unreachable; fix by either removing the post-exception
verification or restructure the test to catch the RegBaseCheckedException
(try-catch) and perform Mockito.verify(signatureService,
Mockito.never()).jwtVerify(...) inside the catch or after asserting no
exception, ensuring you reference the same joinPointMock.getArgs() setup and the
responseSignatureAdvice.responseSignatureValidation invocation and verify
signatureService.jwtVerify interaction appropriately.

In
`@registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/RestClientUtilTest.java`:
- Around line 83-102: Test uses deprecated MediaType.APPLICATION_JSON_UTF8 in
invokeForToken_buildsEntityAndReturnsMap; update the HttpHeaders setup in
RestClientUtilTest to use MediaType.APPLICATION_JSON instead (update the
HttpHeaders instance created for RequestHTTPDTO in that test), ensuring the rest
of the test (RequestHTTPDTO, dto.setHttpHeaders(...), and assertions) remain
unchanged.
🧹 Nitpick comments (7)
registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateHandlerTest.java (1)

186-202: Consider adding more specific assertions to validate error handling behavior.

The test verifies that updateDerbyDB() returns a non-null ResponseDTO when getSortedVersionMappings throws an exception, but it doesn't verify the actual error response content. Consider asserting on the error response details to ensure the error is properly propagated.

 ResponseDTO response = spyHandler.updateDerbyDB();
 
 Assert.assertNotNull(response);
+Assert.assertNotNull(response.getErrorResponseDTOs());
registration/registration-services/src/test/java/io/mosip/registration/test/update/SoftwareUpdateUtilTest.java (1)

102-110: Network-dependent tests may be flaky in CI environments.

Tests at lines 102-110 attempt HTTP connections to http://invalid.invalid/file. While they expect RegBaseCheckedException, network conditions (DNS resolution, timeouts) could cause inconsistent behavior or slow test execution. Consider using a mock HTTP server or a file URL pointing to a non-existent local path for more deterministic testing.

registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_095_ProviderImplTest.java (1)

20-66: Consider extracting repeated reflection code into a reusable helper method.

The reflection pattern for invoking private methods is duplicated across multiple test methods. The helper method invokeGetDeviceSubId (lines 61-66) is a good pattern - consider applying the same approach to getExceptions invocations.

+    private String[] invokeGetExceptions(String[] input) throws Exception {
+        Method method = MosipDeviceSpecification_095_ProviderImpl.class
+                .getDeclaredMethod("getExceptions", String[].class);
+        method.setAccessible(true);
+        return (String[]) method.invoke(mockObject, new Object[]{input});
+    }
+
     `@Test`
     public void testGetExceptions_withNullInput() throws Exception {
-        Method method = MosipDeviceSpecification_095_ProviderImpl.class
-                .getDeclaredMethod("getExceptions", String[].class);
-        method.setAccessible(true);
-
-        String[] result = (String[]) method.invoke(mockObject, new Object[]{null});
+        String[] result = invokeGetExceptions(null);
 
         Assert.assertNull(result);
     }
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java (1)

66-77: Test modifies static shared state without cleanup, which may cause test pollution.

testModifySelectedDeviceInfo adds entries to MosipDeviceSpecificationFactory.getAvailableDeviceInfo() and getDeviceRegistryInfo() but doesn't clean up after itself. This could affect other tests if they run in the same JVM. Consider adding cleanup in an @AfterEach method.

+    `@AfterEach`
+    public void tearDown() {
+        MosipDeviceSpecificationFactory.getAvailableDeviceInfo().clear();
+        MosipDeviceSpecificationFactory.getDeviceRegistryInfo().clear();
+    }
registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/ResponseSignatureAdviceTest.java (1)

324-346: Remove commented-out code and incomplete test setup.

The test fileSignatureValidationTest has commented-out mock setup (lines 334-338) and the actual test assertion is also commented out (line 344). Either complete the test implementation or remove it to avoid confusion.

registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java (1)

553-565: Direct field access bypasses encapsulation - use setter or constructor if available.

Accessing wrapper.deviceInfo = null directly assumes package-private or public field visibility. This creates a fragile test that could break if the field visibility changes. If a setter exists, prefer using it.

registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/RestClientUtilTest.java (1)

111-167: Ensure temp file cleanup even on assertion failures.
If an assertion fails mid-test, the temp file may remain. A try/finally ensures cleanup in all cases.

🧹 Suggested cleanup guard
         File tempFile = File.createTempFile("restclient", ".bin");
         if (tempFile.exists()) {
             tempFile.delete();
         }
+        try {
 
         RequestHTTPDTO dto = new RequestHTTPDTO();
         dto.setUri(new URI("https://example.com/file"));
         dto.setFilePath(tempFile.toPath());
         dto.setHttpHeaders(new HttpHeaders());
         dto.setFileEncrypted(true);
@@
         verify(fileSignatureRepository, atLeastOnce()).save(any(FileSignature.class));
 
-        if (tempFile.exists()) {
-            tempFile.delete();
-        }
+        } finally {
+            if (tempFile.exists()) {
+                tempFile.delete();
+            }
+        }

Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
Copy link

@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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/ResponseSignatureAdviceTest.java (1)

324-346: ⚠️ Potential issue | 🟡 Minor

Incomplete test: actual test invocation is commented out.

The fileSignatureValidationTest method sets up mocks and test data but the actual method call responseSignatureAdvice.fileSignatureValidation(joinPointMock) is commented out on line 344. This test provides no coverage and should either be completed or removed.

🔧 Suggested fix: Either complete the test or remove it
-	`@Test`
-	public void fileSignatureValidationTest() throws RegBaseCheckedException, URISyntaxException, InvalidKeySpecException, NoSuchAlgorithmException {
-		
-		RequestHTTPDTO requestHTTPDTO = new RequestHTTPDTO();
-		requestHTTPDTO.setIsSignRequired(true);
-		requestHTTPDTO.setFileEncrypted(true);
-		requestHTTPDTO.setFilePath(null);
-		requestHTTPDTO.setUri(new URI("/v1/mosip/test"));
-		Object[] args = new Object[1];
-		args[0] = requestHTTPDTO;
-//		Optional<FileSignature> fileSignature = Mockito.mock(fileSignature.getClass());
-//		fileSignature
-		Mockito.when(joinPointMock.getArgs()).thenReturn(args);
-//		Mockito.when(fileSignatureRepository.findByFileName(Mockito.anyString())).thenReturn(fileSignature);
-//		PowerMockito.when(clientCryptoFacade.decrypt()).thenReturn(cryptoCore);
-		JWTSignatureVerifyResponseDto jwtSignatureResponseDto = new JWTSignatureVerifyResponseDto();
-		jwtSignatureResponseDto.setSignatureValid(true);
-		jwtSignatureResponseDto.setMessage(SignatureConstant.VALIDATION_SUCCESSFUL);
-		Mockito.when(signatureService.jwtVerify(Mockito.any())).thenReturn(jwtSignatureResponseDto);
-		
-		//responseSignatureAdvice.fileSignatureValidation(joinPointMock);
-		
-	}
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java (1)

125-160: ⚠️ Potential issue | 🟠 Major

Test does not exercise the actual stream() implementation.

This test creates a full mock, stubs the stream() method, and then only verifies the mock exists. It doesn't test any real behavior—it essentially validates Mockito works. Use the @InjectMocks instance with only dependencies mocked, then call mockObject.stream() and assert the actual result.

🐛 Proposed fix approach
 `@Test`
 public void streamTest() throws Exception{
-    MosipDeviceSpecification_SBI_1_0_ProviderImpl mockedObject = mock(MosipDeviceSpecification_SBI_1_0_ProviderImpl.class);
     
     MdmBioDevice inputBioDevice = new MdmBioDevice();
     // ... setup inputBioDevice ...
     
-    OngoingStubbing<InputStream> actualStream = when(mockedObject.stream(inputBioDevice, "IRIS_DOUBLE")).thenReturn(expectedStream);
-    Assert.assertNotNull(actualStream.getMock());
+    // Mock the helper dependencies instead
+    MosipDeviceSpecification_SBI_1_0_ProviderImpl spy = Mockito.spy(mockObject);
+    Mockito.doReturn(true).when(spy).isDeviceAvailable(inputBioDevice);
+    when(mosipDeviceSpecificationHelper.buildUrl(anyInt(), anyString())).thenReturn("http://localhost/stream");
+    // ... setup HTTP response mock ...
+    
+    InputStream result = spy.stream(inputBioDevice, "IRIS_DOUBLE");
+    assertNotNull(result);
🤖 Fix all issues with AI agents
In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java`:
- Around line 223-243: The test testIsDeviceAvailable invokes
mockObject.isDeviceAvailable(bioDevice) but does not assert its return value;
update the test to capture the result (e.g., boolean available =
mockObject.isDeviceAvailable(bioDevice)) and assert the expected outcome (use
assertTrue/Assertions.assertTrue or assertEquals(true, available)) given the
mocked responses; reference the test method testIsDeviceAvailable, the
MdmBioDevice instance bioDevice, the mocked responses list, and the
mockObject.isDeviceAvailable(...) call when adding the assertion.
🧹 Nitpick comments (8)
registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/ResponseSignatureAdviceTest.java (2)

411-429: Consider adding assertions to verify expected behavior.

The test name implies graceful handling of a missing response body, but there's no assertion verifying the expected behavior. Consider adding a verification to clarify what "graceful handling" means in this context (e.g., verifying jwtVerify is or isn't called, or checking return values).

💡 Suggested assertion
         responseSignatureAdvice.responseSignatureValidation(joinPointMock, linkedMap);
+
+        // Verify expected behavior when response body is null
+        Mockito.verify(signatureService, Mockito.times(1)).jwtVerify(Mockito.any());
 	}

496-497: Consider moving @Rule declaration to the top of the class.

The TemporaryFolder rule is declared at line 496, after the test methods. For consistency with the existing MockitoRule at line 56-57 and standard test class organization, consider moving this rule declaration near the other fields at the top of the class.

registration/registration-services/src/test/java/io/mosip/registration/test/util/restclient/RestClientUtilTest.java (2)

120-176: Consider using TemporaryFolder rule for cleaner temp file management.

The test manually creates and deletes temp files using File.createTempFile() with cleanup in the test body. If an assertion fails, the temp file may not be cleaned up. Consider using JUnit's TemporaryFolder rule (already used in the companion test class) for automatic cleanup.

Additionally, lines 140 and 166 use raw type ResponseExtractor instead of the parameterized form.

💡 Suggested improvement
+    `@Rule`
+    public org.junit.rules.TemporaryFolder tempFolder = new org.junit.rules.TemporaryFolder();
+
     `@Test`
     public void downloadFile_savesSignatureAndSupportsResume() throws Exception {
-        File tempFile = File.createTempFile("restclient", ".bin");
-        if (tempFile.exists()) {
-            tempFile.delete();
-        }
+        File tempFile = tempFolder.newFile("restclient.bin");
+        tempFile.delete(); // Start with non-existent file for initial download test
         
         // ... rest of test ...
         
-        org.springframework.web.client.ResponseExtractor extractor = ...
+        org.springframework.web.client.ResponseExtractor<?> extractor = ...
         
-        if (tempFile.exists()) {
-            tempFile.delete();
-        }
+        // Cleanup handled automatically by TemporaryFolder rule
     }

178-182: Test name doesn't match assertions.

The test is named getHttpRequestFactory_appliesTimeouts but only verifies that the factory is non-null. It doesn't actually verify that the timeouts configured in ApplicationContext.map() were applied to the factory. Consider either renaming to getHttpRequestFactory_returnsNonNull or adding assertions to verify timeout configuration.

💡 Option: Verify timeouts via reflection
     `@Test`
-    public void getHttpRequestFactory_appliesTimeouts() {
+    public void getHttpRequestFactory_returnsConfiguredFactory() {
         SimpleClientHttpRequestFactory factory = restClientUtil.getHttpRequestFactory();
         assertNotNull(factory);
+        // If timeout verification is needed, use reflection or expose accessors
     }
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecificationFactoryTest.java (2)

79-82: Test lacks meaningful assertions.

testAwaitTerminationAfterShutdown calls the method but doesn't verify any behavior. Consider adding assertions or verifications to confirm expected interactions (e.g., verify the executor service methods were called).

💡 Suggested improvement
 `@Test`
 public void testAwaitTerminationAfterShutdown() {
-    factory.awaitTerminationAfterShutdown(mock(ExecutorService.class));
+    ExecutorService mockExecutor = mock(ExecutorService.class);
+    factory.awaitTerminationAfterShutdown(mockExecutor);
+    verify(mockExecutor).shutdown();
 }

243-269: Consider using assertThrows for cleaner exception testing.

The try-catch pattern with fail() works but is verbose. JUnit 5's assertThrows provides a cleaner approach and returns the exception for additional assertions.

💡 Suggested refactor
 `@Test`
 public void testGetSpecVersionByModality_deviceNotFound() throws Exception {
     String modality = "UNKNOWN";

     MosipDeviceSpecificationFactory spyFactory = spy(factory);
     doThrow(new RegBaseCheckedException("404", "Device not found"))
             .when(spyFactory).getDeviceInfoByModality(modality);

-    try {
-        spyFactory.getSpecVersionByModality(modality);
-        fail("Expected RegBaseCheckedException");
-    } catch (RegBaseCheckedException ex) {
-        assertEquals("404", ex.getErrorCode());
-    }
+    RegBaseCheckedException ex = assertThrows(RegBaseCheckedException.class, 
+            () -> spyFactory.getSpecVersionByModality(modality));
+    assertEquals("404", ex.getErrorCode());
 }
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_092_ProviderImplTest.java (2)

63-97: Test validates device info parsing but could have more specific assertions.

The test correctly sets up mocks and verifies the result is not null. Consider adding assertions on the properties of the returned MdmBioDevice objects (e.g., device ID, port) for stronger validation.


124-163: Test name may not accurately reflect the scenario being tested.

The test is named shouldThrowExceptionWhenRCaptureReturnsNoBiometrics, but the setup includes biometrics in the response (line 148). If the exception is expected due to data validation failure or another reason, consider renaming the test to reflect the actual error condition being tested.

Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
Copy link

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java (1)

125-160: ⚠️ Potential issue | 🟠 Major

Test does not exercise the actual implementation - it only mocks the SUT.

Similar to the issue previously flagged in getMdmDevicesTest, this test creates a full mock of MosipDeviceSpecification_SBI_1_0_ProviderImpl and stubs its stream() method. This only verifies that Mockito works, not that the actual implementation behaves correctly.

Use the @InjectMocks instance (mockObject) with only dependencies mocked:

🐛 Proposed fix
-		MosipDeviceSpecification_SBI_1_0_ProviderImpl mockedObject = mock(MosipDeviceSpecification_SBI_1_0_ProviderImpl.class);
 		
 		MdmBioDevice inputBioDevice = new MdmBioDevice();
 		inputBioDevice.setCallbackId("http://127.0.0.1:4501");
 		// ... setup inputBioDevice ...
 		
-		OngoingStubbing<InputStream> actualStream = when(mockedObject.stream(inputBioDevice, "IRIS_DOUBLE")).thenReturn(expectedStream);
+		// Mock the helper dependencies instead
+		when(mosipDeviceSpecificationHelper.buildUrl(anyInt(), anyString())).thenReturn("http://localhost/stream");
+		when(mosipDeviceSpecificationHelper.getJPEGByteArray(any(), anyLong())).thenReturn(byteData);
 		
-		Assert.assertNotNull(actualStream.getMock());
+		InputStream result = mockObject.stream(inputBioDevice, "IRIS_DOUBLE");
+		assertNotNull(result);
🤖 Fix all issues with AI agents
In
`@registration/registration-services/src/test/java/io/mosip/registration/test/mdm/service/MosipDeviceSpecification_SBI_1_0_ProviderImplTest.java`:
- Around line 242-244: The test currently asserts assertNotNull(result) for the
primitive boolean returned by mockObject.isDeviceAvailable(bioDevice) in
MosipDeviceSpecification_SBI_1_0_ProviderImplTest; replace that meaningless
null-check with a boolean assertion that reflects the expected behavior—use
assertTrue(result) if the device should be available or assertFalse(result) if
it should not be available (and ensure the test imports the correct JUnit
assertion methods if missing).
- Around line 173-186: The test creates an SbiDigitalId instance but never
attaches it to the MdmSbiDeviceInfoWrapper (deviceInfo), so the setup is
ineffective; fix by setting the digitalId on deviceInfo using the wrapper's
appropriate setter or adder (e.g., deviceInfo.setDigitalId(...) or
deviceInfo.getDigitalIds().add(...)) before the
when(mosipDeviceSpecificationHelper.getDeviceInfoDecoded(...)) stub so the
returned deviceInfo contains the configured SbiDigitalId.

Signed-off-by: GOKULRAJ136 <110164849+GOKULRAJ136@users.noreply.github.com>
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.

1 participant