【问题标题】:Stubbing is not covering my method in unit testing存根没有涵盖我在单元测试中的方法
【发布时间】:2019-07-29 15:53:44
【问题描述】:

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

服务类

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

}

【问题讨论】:

  • 你在使用spring-boot吗?

标签: java unit-testing junit mockito stubbing


【解决方案1】:

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

但是,当我存根方法时,没有行覆盖 测试类。

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

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

@Autowired
private Client client;

所以你可以模拟或存根它。

【讨论】:

    【解决方案2】:

    如果您使用的是 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"));
        }
    
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-13
      • 1970-01-01
      • 2016-04-25
      相关资源
      最近更新 更多