'Junit test Java static method

I'm bit newbie to Java. Is it possible to Unit test scenario like this?

public class exampleClass {

    public static StatsDClient getClient() {
        return new NonBlockingStatsDClientBuilder()
                .prefix("statsd1")
                .hostname("localhost")
                .port(4000)
                .build();
    }
}


Solution 1:[1]

Since you have mentioned the StatsDClient doesn't have any getters, can you override the equals method of StatsDClient something like this. This way you'd not need getters

public class StatsDClient {
    private String hostName;
    private String prefix;
    private int port;
 
    public StatsDClient(String hostName, String prefix, int port) {
        this.hostName = hostName;
        this.prefix = prefix;
        this.port = port;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!this.getClass().equals(obj.getClass())) {
            return false;
        }
        StatsDClient otherStatsClient = (StatsDClient) obj;

        return this.hostName.equals(otherStatsClient.hostName) && this.prefix.equals(otherStatsClient.prefix)
                && this.port == otherStatsClient.port;
    }
}

You can build expected StatsDClient and assert against the result

@Test
public void verifyStatsDClient() {
    StatsDClient actualStatsDClient = exampleClass.getClient();
    StatsDClient expectedStatsDClient = new StatsDClient("expectedHost","expectedPrefix",expectedPort);
    assertEquals(expectedStatsDClient,actualStatsDClient);
}

Since equals is overridden, assertEquals should implicitly calls the equals and verifies

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 HariHaravelan