首页 > 解决方案 > 模拟对象返回 null

问题描述

JUnit 测试类:

public class TestingClass {

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity entity;

    @Mock
    private ResponseEntity<Resource> responseEntity;

    @Before
    public void setup() {

        MockitoHelper.initMocks(this);

    }

    @Test
    public void getDataTest() {

        ClassToTest c = new ClassToTest(restTemplate);

        when(restTemplate.exchange("http://testing", HttpMethod.GET, entity, Resource.class)).thenReturn(responseEntity);
        c.getData("http://testing");

    }

}

正在测试的类:

import org.jsoup.helper.Validate;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.util.Optional;

public class ClassToTest {

    private HttpHeaders headers;
    private RestTemplate restTemplate;

    public ClassToTest(RestTemplate restTemplate){
        this.restTemplate = restTemplate;
        headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
    }

    public Optional<InputStream> getData(final String mediaUrl) {

        Validate.notEmpty(mediaUrl);

        final String requestJson = "{}";
        final HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
        Optional inputStreamOptional = Optional.empty();

        try {
            final ResponseEntity<Resource> responseEntity = restTemplate.exchange(mediaUrl, HttpMethod.GET, entity, Resource.class);
            System.out.println(responseEntity);
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        return inputStreamOptional;
    }
}

结果System.out.println(responseEntity);null

应该responseEntity设置为它的模拟值并返回(而不是返回 null 的当前行为),如在中配置的:when(restTemplate.exchange("http://testing", HttpMethod.GET, entity, Resource.class)).thenReturn(responseEntity);

那么什么时候c.getData("http://testing");调用模拟responseEntity返回?

改为更新使用:

when(restTemplate.exchange(Matchers.eq("http://testing"), Matchers.eq(HttpMethod.GET), Matchers.isA(HttpEntity.class), Matchers.eq(Resource.class))).thenReturn(responseEntity);

标签: javajunitmockingmockito

解决方案


它很可能返回 null 因为您的参数定义when和实际参数不同。entity在您的情况下,您的模拟和HttpEntity您在被测代码中创建的很可能既不相同也不相等。所以你需要扩大你对when-definition 的期望。您应该在定义中使用 Matchers 并且可以isA(HttpEntity.class)用于您的实体。


推荐阅读