有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java存根并没有涵盖我在单元测试中的方法

我试图通过使用存根方法实现单元测试。 但是,当我存根该方法时,测试类没有行覆盖

服务等级

@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) 个答案

  1. # 1 楼答案

    如果您使用的是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"));
        }
    
     }
    
  2. # 2 楼答案

    单元测试中的子绑定指的是在对组件进行单元测试时不希望它干扰的依赖项
    实际上,您希望对组件行为进行单元测试,并模拟或存根可能对其产生副作用的依赖关系
    在这里,您将测试该类。这毫无意义

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

    在使用ServiceStub实例的情况下执行测试,在单元测试方面当然不包括Service代码

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

    @Autowired
    private Client client;
    

    这样你就可以嘲笑它或者把它存根