在单元测试中存根并不能覆盖我的方法

时间:2019-03-07 17:04:06

标签: java unit-testing junit mockito stubbing

我正在尝试使用存根方法进行单元测试。 但是,当我对方法进行存根处理时,没有测试类的行覆盖。

服务等级

@Service
@Slf4j
public class Service {

    @Autowired
    private Client client;

    private String doclinkUrl = "www.website.com"

    public byte[] downloadContent(String objectId) {
        String url = doclinkUrl + "documents/" +objectId + "/binary";
        return client.target(url).request().get(byte[].class);
    }
}

存根服务类

public class ServiceStub extends Service {

    @Override
    public byte[] downloadContent(String objectId) {
        return "test".getBytes();
    }

}

测试服务等级

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @InjectMocks
    private Service testee;

    @Test
    public void testDownloadContent(){
        testee = new ServiceStub();
        Assert.assertNotNull(testee.downloadContent("objectId"));
    }

}

2 个答案:

答案 0 :(得分:1)

单元测试中的Subsub是指在对组件进行单元测试时不希望其干扰的依赖项。 实际上,您想对组件行为进行单元测试,并模拟或存根可能对其产生副作用的依赖项。
在这里,您可以对被测类进行存根。这没有道理。

  

但是,当我对方法进行存根分析时,   经过测试的课程。

执行使用ServiceStub实例的测试当然不会涵盖Service代码的单元测试。

Service类中,您要隔离的依赖项是:

@Autowired
private Client client;

因此您可以模拟或存根。

答案 1 :(得分:0)

如果您使用的是Spring Boot,则可以进行大部分集成测试,并且仅使用@MockBean来模拟外部API调用

@SpringBootTest
@RunWith(SpringRunner.class)
public class ServiceTest {

@Autowired
private Service service;

@MockBean
 private Client client;

@Test
public void testDownloadContent(){

    //given(this.client.ArgumentMatchers.any(url) //addtional matchers).willReturn(//somebytes);
    service = new ServiceStub();
    Assert.assertNotNull(testee.downloadContent("objectId"));
    }

 }
相关问题