【问题标题】:How to perform unit testing in android studio如何在 android studio 中进行单元测试
【发布时间】:2017-04-10 07:05:43
【问题描述】:

我在 android 中制作了一个示例应用程序,并在其中包含了 aar 文件,并且我对该应用程序进行了单元测试,是否可以对示例应用程序进行单元测试?

【问题讨论】:

标签: java unit-testing android-studio aar


【解决方案1】:

考虑下面的单元测试示例类

public class SampleUnitTestClass {

    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }
}

创建类后使用快捷键Ctrl+Shift+T创建一个新的Test类对应你的示例类。

  • 点击创建新测试
  • 在单元测试类中选择所需的方法并单击确定(如果需要,您还可以更改类名称、目标包、测试库)
  • 选择目标目录并点击确定
  • 将创建一个单元测试类

    public class SampleUnitTestClassTest {
    @Test
    public void add() throws Exception {
    
    }
    
    @Test
    public void subtract() throws Exception {
    
    }
    

    }

在此处写下您的测试逻辑并确定您的答案。例如:

public class SampleUnitTestClassTest {
@Test
public void add() throws Exception {
    SampleUnitTestClass testClass = new SampleUnitTestClass();
    int answer = testClass.add(2,7);
    assertEquals("Addition of 2 positive integers",9,answer);
}

@Test
public void subtract() throws Exception {
    SampleUnitTestClass testClass = new SampleUnitTestClass();
    int answer = testClass.subtract(2,7);
    assertEquals("Subtraction of 2 positive integers",-5,answer);
}

}

添加更多方法以包含负值、空值等并断言答案。

【讨论】:

    【解决方案2】:

    对于单元测试,您可以使用 Mockito,如果您还需要一些 Android 资源,您可以阅读 Robolectric。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      • 2016-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-27
      相关资源
      最近更新 更多