问题
I am using Android Studio 1.2
Say I have a simple method add in some class MyAdder
public int add(int a,int b) {
return a+b;
}
I want to perform the unit test and use assertions to perform the test for the above-mentioned code.
I found it tough, to begin with, Testing Fundamentals from the official DEV site so a sample code or a detailed tutorial for performing unit tests would be appreciated.
回答1:
Two types of tests are supported, available in a drop-down menu in the Build Variants
tool window of Android Studio:
- Android Instrumentation Tests: integration/functional testing using a running app on a device or on an emulator, often referred to as Android Tests
- Unit Tests: plain JUnit tests that run on a local JVM, with a stubbed android.jar provided
The Testing Fundamentals page mostly discusses Android Instrumentation Tests, with which, as you noted, is a bit tough to get started.
For your question, however, you just need Unit Tests.
From the Unit testing support page:
- Update build.gradle to use the android gradle plugin version 1.1.0-rc1 or later (either manually in build.gradle file or in the UI in File > Project Structure)
- Add necessary testing dependencies to app/build.gradle
dependencies {
testCompile "junit:junit:4.12"
}
- Enable the unit testing feature in Settings > Gradle > Experimental. (enabled and no longer experimental as of Android Studio 1.2)
- Sync your project.
- Open the "Build variants" tool window (on the left) and change the test artifact to "Unit tests".
- 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.
Here is some sample code to test the instance method in your question (replace com/domain/appname
with the path created by your package name):
projectname/app/src/test/java/com/domain/appname/MyAdderTest.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyAdderTest {
private MyAdder mMyAdder;
@Before
public void setUp() throws Exception {
// Code that you wish to run before each test
mMyAdder = new MyAdder();
}
@After
public void tearDown() throws Exception {
// Code that you wish to run after each test
}
@Test
public void testAdd() {
final int sum = mMyAdder.add(3, 5);
assertEquals(8, sum);
}
}
来源:https://stackoverflow.com/questions/30168248/unit-testing-in-android