1

I have the below method in the @Configuration class and I need to write JUnit for this. Can anyone please guide me to achieve the JUnit test case?

@Bean
@Profile({"!test & !local"})
@Primary
public DiscoveryClient.DiscoveryClientOptionalArgs getClient() {
    try {
        DiscoveryClient.DiscoveryClientOptionalArgs args = new DiscoveryClient.DiscoveryClientOptionalArgs();
        args.setAdditionalFilters(Collections.singletonList(new HTTPBasicAuthFilter(this.username, this.password)));
        args.setSSLContext(sslContext());
        System.setProperty("javax.net.ssl.trustStore", this.truststorePath);
        System.setProperty("javax.net.ssl.trustStorePassword", this.trustStorePassword);

        return args;
    } catch (IOException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) {
        throw new IllegalStateException("Unable to instantiate ssl context or authentication", e);
    }
}
João Dias
  • 16,277
  • 6
  • 33
  • 45
Sdcoder
  • 33
  • 2
  • 4
  • Please don't just ask us to solve the problem for you. Show us how you tried to solve the problem yourself, then show us exactly what the result was, and tell us why you feel it didn't work. Give us a clear explanation of what isn't working and provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). Read [How to Ask a good question](https://stackoverflow.com/help/how-to-ask). Be sure to take the tour and read this. – jasie Dec 16 '21 at 12:44

1 Answers1

1

First, consider what do you want to test. Successful creation of DiscoveryClient? Sure. Taking a pragmatic stance, I would even avoid Spring in that case:

public class DiscoveryClientConfigTest {
    
    @Test
    public void testGetClient() {
        DiscoveryClientConfig config = new DiscoveryClientConfig();
        DiscoveryClientOptionalArgs client = config.getClient();
        // Assert some state of the client
    }

        
    @Test
    public void testGetClient_FailsToCreateClient() {
        // Whatever exception you expect...
        assertThrows(IOException.class, () -> {
            DiscoveryClientConfig config = new DiscoveryClientConfig();
            config.getClient();
        });
    }
}

If you want to test it while it affects some other components, then that's out of the scope of a unit test.

João Dias
  • 16,277
  • 6
  • 33
  • 45
Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85