Stubbing 没有覆盖我在单元测试中的方法

Stubbing is not covering my method in unit testing

我正在尝试使用存根方法来实施单元测试。 但是,当我对该方法进行存根时,没有测试class 的行覆盖。

服务Class

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

存根服务Class

public class ServiceStub extends Service {

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

}

测试服务Class

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @InjectMocks
    private Service testee;

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

}

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

However, when I stub the method, there is no line coverage of the tested class.

在使用 ServiceStub 实例的情况下执行测试当然不会在单元测试方面涵盖 Service 代码。

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

@Autowired
private Client client;

因此您可以模拟或存根它。

如果您使用 spring 引导,您可以对大部分部分进行集成测试,并且仅使用 @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"));
    }

 }