2015-03-02 210 views
0

道歉可能看起来像一个愚蠢的职位。使用Mockito进行测试

如何在最新版本的Android Studio SDK上运行Mockito? 并且你可以使用Android Studio平台使用Mockito运行多个测试吗?

我在Eclipse上使用Mockito并在同一窗口中运行多达6个测试。但我试图弄清楚如何在Android Studio平台上执行此操作,并且找不到任何网站或教程的答案。

+0

没有什么特别的。你只需从JUnit中'TestCase',在'setUp'中准备你的模拟。要运行测试,您必须使用Android Test Runner(您可以从IDE中选择它)。请注意,Android SDK包含许多不能被嘲笑的最终课程。 – Eugene 2015-03-02 14:52:42

+0

啊对了。谢谢,我从来不知道。我会密切关注那 – Peter3514608 2015-03-02 16:02:58

回答

1

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和Mockito 2.0.5测试版在Android Studio 1.1中进行单元测试,并且没有任何问题:

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

至于在同一时间运行多个测试,你的意思是测试用例?测试课程?测试套件?请澄清,如有需要,我会更新我的答案。

+0

是的,在Eclipse中,我有多个测试用例测试程序的不同位。我想知道Android是否与Mockito一样工作.................我使用了上面的依赖关系,并且出现如下错误:...... .......错误检索项目找不到匹配给定名称'theme.appcompat.light'的资源。darkactionbar' – Peter3514608 2015-03-02 15:50:52

+0

我修正了我遇到的错误....感谢所有你们。我将在Android上玩Mockito :) – Peter3514608 2015-03-02 16:10:11

0

在您的应用程序中打开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

单元测试应该是应用/ src目录/ androidTest /文件夹下。

+0

谢谢,我会试试:) – Peter3514608 2015-03-02 15:28:18

+0

我创建了Mockito依赖关系,就像你建议的那样。它与Android Studios同步,但它由于某种原因带来了Styles.xml文件,并且正在生成和错误: – Peter3514608 2015-03-02 15:33:11

+1

单元测试应该在src/test /或src/androidTest /下,具体取决于你想要的位置运行它们,本地JVM或设备/仿真器。 – 2015-03-06 13:43:42

0

我可以验证接受的答案是正确的,但只是为了进一步答案,将有一个androidTest文件夹旁边的主文件夹。通常你会使用androidTest文件夹进行检测。只要确保在构建变体面板下,测试工件:被选择为“单元测试”,否则build.gradle中的testCompile将不起作用。我花了一段时间才弄清楚这一部分。

希望它有帮助。