使用 Mockito 进行测试

Testing using Mockito

为看似愚蠢的事情道歉post。

如何在最新版本的 Android Studio SDK 上 运行 Mockito? 您可以使用 Android Studio 平台使用 Mockito 运行 进行多项测试吗?

我在 Eclipse 上使用了 Mockito,运行 在同一个 window 中进行了多达 6 次测试。但我正试图找出如何在 Android Studio 平台上执行此操作,但我找不到任何网站或教程提供答案。

在您的应用程序中打开您的 app/build.gradle 文件并将 mockito 添加到依赖项中,如果没有依赖项,您可以继续创建它。

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'org.mockito:mockito-core:1.10.8'
    androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.1'
}

然后在您的单元测试中,只需像往常一样创建一个模拟对象: http://site.mockito.org/#how

单元测试应该在 app/src/androidTest/ 文件夹下。

Android Studio 1.1 现在内置了对单元测试的支持。来自 Unit testing support - Android Tools Project Site:

Unit tests run on a local JVM on your development machine. Our gradle plugin will compile source code found in src/test/java and execute it using the usual Gradle testing mechanisms. At runtime, tests will be executed against a modified version of android.jar where all final modifiers have been stripped off. This lets you use popular mocking libraries, like Mockito.

You will have to specify your testing dependencies in the build.gradle file of your android module. For example:

dependencies {
  testCompile 'junit:junit:4.12'
  testCompile "org.mockito:mockito-core:1.9.5"
}

该页面还包含设置 Android Studio 进行单元测试的分步指南,包括为单元测试创​​建单独的目录:

  1. Create a directory for your testing source code, i.e. src/test/java. You can do this from the command line or using the Project view in the Project tool window. The new directory should be highlighted in green at this point. Note: names of the test source directories are determined by the gradle plugin based on a convention.

我目前正在使用 junit 4.12 and Mockito 2.0.5 beta 在 Android Studio 1.1 中进行单元测试,并且没有遇到任何问题:

dependencies {
    // ...
    testCompile 'junit:junit:4.12'
    testCompile "org.mockito:mockito-core:2.0.5-beta"
}

就运行同时进行多项测试而言,你是指测试用例吗?测试类?测试套件?请澄清,如果需要,我会更新我的答案。

我可以验证接受的答案是否正确,但为了进一步了解答案,您的主文件夹旁边将有一个 androidTest 文件夹。通常您会使用 androidTest 文件夹进行仪器测试。只需确保在 build variants 面板下,将 Test Artifact: 选择为 "Unit Tests" 否则 build.gradle 中的 testCompile 将无法运行。我花了一段时间才弄清楚这部分。

希望对您有所帮助。