1

我正在使用 Mockito 3.6 来利用他们的 mockStatic 方法。我在模拟一个也是用于测试的主类的类时遇到问题。

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);
    }
}

这是我的测试课

@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());
    }
}

由于MainClass使用的是mockStatic和injectMock,所以调用buildURI的时候总是返回null,这在创建HttpRequest的时候是不能接受的。

编辑:为了澄清我的问题,我从环境变量中获取主机和端口,运行此测试时将为空,并且调用new URI()不允许空值。

4

0 回答 0