【问题标题】:how to write Junit test case for testing usage of a Google api(Directory api)如何编写 Junit 测试用例以测试 Google api(目录 api)的使用
【发布时间】:2015-08-14 04:20:04
【问题描述】:

目前代码是这样开始的

Directory directory = DirectoryServiceFactory.getDirectoryService();

directory.groups().get(someEmail).execute();

我不确定如何为它编写测试用例,或者我什至应该编写一个测试用例。在这里写一个测试用例到底意味着什么。

【问题讨论】:

    标签: junit junit4 junit-rule


    【解决方案1】:

    理论上,您应该只测试自己的代码。如果您必须测试您的框架,那么您使用的是错误的框架。诸如连接和使用 Google API 之类的远程操作只能在集成测试中进行测试,而不是在单元测试中进行测试。

    因此,在这种情况下,我会尝试以某种方式封装您自己的代码,允许您放置连接 Google API 的类的模拟版本并在其中执行某些操作,例如通过编写 @987654321 @ 或类似的东西:

    public interface GoogleAPIConnector {
    
        void connect();
        String doSomeWork(String email);
    
    }
    

    您将创建此接口的一个“真实”实现,它实际上连接到 Google 并执行实际工作。测试这将是集成测试的范围。可能看起来像这样......

    public class GoogleAPIConnectorImpl {
    
        private Directory directory;
    
        @Override
        public void connect() {
            this.directory = DirectoryServiceFactory.getDirectoryService();
        }
    
        @Override
        public String doSomeWork(String email){
            return this.directory.groups().get(email).execute();
        }
    
    }
    

    对于单元测试,您将改为使用返回“假”数据而不是真实数据的模拟对象,允许您在假设 google 连接有效的情况下运行测试,测试您围绕它编写的所有内容,例如(与 Mockito):

    GoogleAPIConnector connector = mock(GoogleAPIConnector.class);
    when(connector.doSomeWork("someone@example.com")).thenReturn("hello world");
    
    SomeClass someClass = new SomeClass(""someone@example.com");
    someClass.setConnector(connector);
    
    String result = someClass.work();
    assertThat(result, equalTo("hello world");
    
    verify(connector, times(1)).doSomeWork("someone@example.com");
    

    这样,您的单元测试将很快并且不依赖于 Google API(如果您的网络出现故障,它们仍然会成功)。您的集成测试速度较慢并且依赖于 Google API,但由于它们不必经常运行(并且不必使构建失败),这没关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 2019-11-01
      • 2017-12-29
      • 1970-01-01
      相关资源
      最近更新 更多