Mocking Unirest与Mockito

vs91vp4v  于 2022-11-08  发布在  其他
关注(0)|答案(5)|浏览(169)

我正处于编程的起步阶段,我想问一下如何用Mockito模拟对象,更具体地说,是Uniest响应。假设我有一个数据库,我不想每次测试时都打扰它,我想用Mockito来做这件事,但问题是我不知道如何创建假的“httpResponse”对象,它会返回。为了提供一些上下文,我附上了我的代码:

/**
 * This method lists the ID of the activity when requested.
 *
 * @return the list of all activities
 */
public  JSONArray getActivites() {
    HttpResponse<JsonNode> jsonResponse = null;
    try {
        jsonResponse = Unirest
                .get("http://111.111.111.111:8080/activity")
                .header("accept", "application/json")
                .asJson();
    } catch (UnirestException e) {
        System.out.println("Server is unreachable");
    }

    JSONArray listOfActivities = jsonResponse.getBody().getArray();
    return listOfActivities;
}

所以我想的是模拟Uniest,然后当调用.get方法时,我会返回一个假的HttpResponse,问题是,我不知道如何做,我在网上看过,不能真正理解它。有没有可能用实际的数据库做一次,然后“提取”信息,每次都用它来测试?

hk8txs48

hk8txs481#

PowerMockRunner、PowerMockito和Mockito的范例程式码片段

@RunWith(PowerMockRunner.class)
    @PrepareForTest({ Unirest.class})
    public class TestApp{

      @Before
      public void setup() {
        PowerMockito.mockStatic(Unirest.class);
      }

      @Test
      public void shouldTestgetActivites() throws UnirestException {
        when(Unirest.get(Client.DEFAULT_BASE_URL)).thenReturn(getRequest);
        when(getRequest.asJson()).thenReturn(httpResponse);
        when(httpResponse.getStatus()).thenReturn(Integer.valueOf(200));

        assertThat(something).isEqualTo(true);
      }

    }
z6psavjg

z6psavjg2#

您可以将调用 Package 在一个 Package 类中,而不是直接调用一个静态成员,该 Package 类可以基于某些参数提供一个HttpResponse。这是一个很容易在Mockito中被模仿的接口。

/**
 * This is a wrapper around a Unirest API.
 */
class UnirestWrapper {

    private HttpResponse<JsonNode> getResponse(String accept, String url) {
        try {
            return Unirest
                .get(url)
                .header("accept", accept)
                .asJson();
        } catch (UnirestException e) {
            System.out.println("Server is unreachable");
        }
        // Or create a NULL HttpResponse instance.
        return null;
    }
}

private final UnirestWrapper unirestWrapper;

ThisClassConstructor(UnirestWrapper unirestWrapper) {
    this.unirestWrapper = unirestWrapper;
}

/**
 * This method lists the ID of the activity when requested.
 *
 * @return the list of all activities
 */
public JSONArray getActivites() {
    HttpResponse<JsonNode> jsonResponse = this.unirestWrapper.getResponse("http://111.111.111.111:8080/activity", "application/json");

    if (jsonResponse == null) {
        return null;
    }

    JSONArray listOfActivities = jsonResponse.getBody().getArray();
    return listOfActivities;
}

或者你可以用力量模拟...

n53p2ov0

n53p2ov03#

同时,原始作者提供了unirest-mocks的模拟支持:
玛文:

<dependency>
    <groupId>com.konghq</groupId>
    <artifactId>unirest-mocks</artifactId>
    <version>LATEST</version>
    <scope>test</scope>
</dependency>

用法:

class MyTest {
    @Test
    void expectGet(){
        MockClient mock = MockClient.register();

        mock.expect(HttpMethod.GET, "http://zombo.com")
                        .thenReturn("You can do anything!");

        assertEquals(
            "You can do anything!", 
            Unirest.get("http://zombo.com").asString().getBody()
        );

        //Optional: Verify all expectations were fulfilled
        mock.verifyAll();
    }
}
7dl7o3gd

7dl7o3gd4#

你可以用Mockito.mock(HttpResponse.class)来模拟HttpResponse,并在获取这个响应的主体时放入,以获取你的json。例如:

HttpResponse response = Mockito.mock(HttpResponse.class);    
when(response.getBody()).thenReturn(readFileContent("my_response.json"));

这个'readFileContent'只是一个方法,用来读取一个文件,我把我的响应放在这个文件中。你可以把你的json放在那里进行比较

wxclj1h5

wxclj1h55#

我使用JUnit5和Mockito解决了类似的任务。待测类:

@Service
@RequiredArgsConstructor
@Profile("someProfile")
@Slf4j
public class SomeService {

    @Value("${value1}")
    private final String value1;

    @Value("${value2}")
    private final String value2;

    private final ObjectMapper mapper;
    private final CommonUtil commonUtil;

    public boolean methodUnderTest(String inputValue) {
        HttpResponse<String> result;
        //some logic 
        try {
            result = Unirest.get("url")
                    .header(header, value)
                    .routeParam("param", paramValue)
                    .asString();
            if (result.getStatus() != 200) {
                throw new MyException("Message");
            }
            //some logic
        } catch (Exception e) {
            log.error("Log error", e);
            //some logic
        }
    }
}

并测试:

@ExtendWith(MockitoExtension.class)
class SomeServiceTest {
    @Mock
    private CommonUtil commonUtil;
    @Mock
    private ObjectMapper mapper;
    @Mock
    HttpResponse httpResponse;
    @Mock
    GetRequest request;

    private SomeService serviceUnderTest;

    @BeforeEach
    void setUp() {
        this.serviceUnderTest = new SomeService("url", "valu1", mapper, commonUtil);
    }

    @Test
    void methodUnderTest_whenSmth_ThenSmth() throws UnirestException {
        try (MockedStatic<Unirest> unirest = Mockito.mockStatic(Unirest.class)) {
            unirest.when(() -> Unirest.get(anyString()))
                    .thenReturn(request);

            Mockito.when(commonUtil.encodeValue(Mockito.anyString())).thenReturn("123");

            Mockito.when(request.header(anyString(), anyString())).thenReturn(request);
            Mockito.when(request.routeParam(anyString(), anyString())).thenReturn(request);
            Mockito.when(request.asString()).thenReturn(httpResponse);

            Mockito.when(httpResponse.getStatus()).thenReturn(200);
            Mockito.when(httpResponse.getBody()).thenReturn("true");
            assertTrue(serviceUnderTest.methodUnderTest("123"));
        }
    }
 }

相关问题