Spring / Spring CredHub Interview questions
How do you unit test a service that depends on CredHubCredentialOperations?
Mock the interface with Mockito rather than standing up a real CredHub server, and inject it the same way production code would — typically through a constructor:
@ExtendWith(MockitoExtension.class) class OrderCredentialServiceTest { @Mock CredHubCredentialOperations credentialOperations; @InjectMocks OrderCredentialService service; @Test void returnsStoredPassword() { CredentialDetails<PasswordCredential> details = new CredentialDetails<>("id", credentialName, CredentialType.PASSWORD, new PasswordCredential("s3cret")); when(credentialOperations.getByName(credentialName, PasswordCredential.class)) .thenReturn(details); assertThat(service.fetchDbPassword()).isEqualTo("s3cret"); } }
For the failure path, have the mock throw a CredHubException (or a stub with the status code you care about) instead of returning a value, so you can assert the service handles a missing or unreachable credential the way you intend — that's usually the more important test, since it's the path production code is more likely to get wrong.
More Related questions...