java—如何从外部库创建测试对象

wswtfjt7  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(320)

我有一个类用于解析api请求中给出的json响应,该请求是使用restlet框架生成的。
负责读取json的方法从这个框架中获取一个对象,一个表示, public QueryResponse readResponse(Representation repr) ,我想测试一下
我的问题是,在我的junit测试中如何将一个有效的表示对象传递到这个方法中,考虑到我不知道它是如何从api调用构造的,我是否必须在测试中实现调用本身来检索一个可行的对象,或者是否有其他方法?

1mrurvl1

1mrurvl11#

对于单元测试,使用mockito这样的模拟框架:

import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.restlet.representation.Representation;

import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
public class RestletTest {
    @Mock
    private Representation representation;

    @Test
    public void demonstrateMock() {
        when(representation.getAvailableSize()).thenReturn(1024l);

        ClassToTest t = new ClassToTest();
        assertThat(t.callRepresentation(representation), Matchers.is(1024l));
    }
}

class ClassToTest {
    public long callRepresentation(Representation representation) {
        return representation.getAvailableSize();
    }
}

相关问题