1

I'm using Mockito 3.6 to take advantage of their mockStatic method. I am having issue when mocking a class that is also the main class to be used for testing.

public class MainClass{
    private HttpClient httpClient;

    public String sendRequest(){
        HttpRequest request = HttpRequest.newBuilder()
            .uri(buildUri(System.getEnv("host"), System.getEnv("port")))
            .GET().build()
        HttpResponse<String> response = httpClient.send(request, ofString());
        return response.body
    }

    public static URI buildURI(String host, String path) throws URISyntaxException {
        return new URI("http", host, path, null);
    }
}

This is my test class

@ExtendWith(MockitoExtension.class)
public class MainClassTest {
    @Spy
    private ObjectMapper mapper = new ObjectMapper();
    @Mock
    private HttpClient httpClientMock;
    @InjectMocks
    private MainClass mainClass;

    private MockedStatic<MainClass> systemMock;

    @BeforeEach
    void setUp() {
        systemMock = mockStatic(MainClass.class);
    }

    @AfterEach
    void tearDown() {
        systemMock.close();
    }

    @Test
    void sendRequest_successful(){
        HttpResponse response = mock(HttpResponse.class);
        when(response.body()).thenReturn("Hello, world!");
        when(httpClientMock.send(any(HttpRequest.class), any())).thenReturn(response);
        systemMock.when(() -> MainClass.buildURI(anyString(), anyString()))
                .thenReturn(URI.create("http://host.com/path"));

        assertEquals("Hello, world!", mainClass.sendRequest());
    }
}

Since the MainClass is being used to be mockStatic and injectMock, when calling buildURI, it always return null, which is not acceptable when creating HttpRequest.

Edit: To clarify my issue, I'm getting the host and port from environment variable, which will be null when running this test, and calling new URI() does not allow null values.

Dariell Bowo
  • 21
  • 1
  • 6

0 Answers0