Gradle 기반 구성을 사용할 때 Android Studio (IntelliJ)에서 간단한 JUnit 테스트 실행
Android Studio/IntelliJ기존 Android프로젝트 를 빌드하는 데 사용 하고 있으며 간단한 JUnit단위 테스트 를 추가하고 싶습니다 . 이러한 테스트를 추가 할 올바른 폴더는 무엇입니까?
안드로이드 Gradle와 플러그인을 정의 디렉토리 구조 src/main/java의 주요 소스 코드와 src/instrumentTest/java에 대한 Android테스트합니다.
instrumentTest에 내 JUnit 테스트를 추가하려고해도 효과가 없었습니다. 나는 그것을 Android테스트 로 실행할 수 있지만 (그 디렉토리가 보이는 것입니다) 내가 찾고있는 것이 아닙니다-나는 단지 간단한 JUnit테스트 를 실행하고 싶습니다 . 이 클래스에 대한 JUnit 실행 구성을 만들려고 시도했지만 작동하지 않았습니다 Android. Source 대신 Test 로 플래그가 지정된 디렉터리를 사용하고 있기 때문 입니다.
새 소스 폴더를 만들고 프로젝트 구조에 표시하면 다음 IntelliJ에 gradle 빌드 파일에서 프로젝트 구성을 새로 고칠 때 지워 집니다.
gradle 기반 Android 프로젝트에서 JUnit 테스트를 구성하는 더 적절한 방법은 무엇입니까 IntelliJ? 이를 위해 사용할 디렉토리 구조는 무엇입니까?
Android Studio 1.1에서 답은 이제 간단합니다. http://tools.android.com/tech-docs/unit-testing-support
일반적으로 할 수 없습니다. 모든 테스트가 기기 (Roboolectric 제외)에서 실행되어야하는 Android의 세계에 오신 것을 환영합니다.
주된 이유는 실제로 프레임 워크의 소스가 없기 때문입니다. IDE가 테스트를 로컬에서 실행하도록 설득하더라도 즉시 "Stub! Not Implemented"예외가 발생합니다. "왜?" 궁금할까요? android.jarSDK가 제공하는 것은 실제로 모두 스텁 처리되어 있기 때문에 모든 클래스와 메서드가 있지만 모두 예외가 발생합니다. API를 제공하기위한 것이지만 실제 구현을 제공하기위한 것은 아닙니다.
의미있는 테스트를 실행할 수 있도록 많은 프레임 워크를 구현하는 Robolectric 이라는 멋진 프로젝트가 있습니다. 좋은 모의 프레임 워크 (예 : Mockito)와 함께 사용하면 작업을 관리 할 수 있습니다.
Gradle 플러그인 : https://github.com/robolectric/robolectric-gradle-plugin
소개
robolectric 2.4는 최신 버전이며 appcompat v7라이브러리를 지원하지 않습니다 . robolectric 3.0 릴리스에 지원이 추가 될 예정입니다 ( 아직 ETA 없음 ). 또한 ActionBar Sherlockrobolectric에 문제를 일으킬 수 있습니다.
Android Studio에서 Robolectric을 사용하려면 두 가지 옵션이 있습니다.
(옵션 1)-Java 모듈을 사용하여 Android Studio에서 JUnit 테스트 실행
이 기술은 Android 모듈에 대한 종속성이있는 모든 테스트에 Java 모듈을 사용하고 몇 가지 마법이있는 사용자 지정 테스트 실행기를 사용합니다.
지침은 여기에서 찾을 수 있습니다 : http://blog.blundellapps.com/how-to-run-robolectric-junit-tests-in-android-studio/
또한 Android 스튜디오에서 테스트를 실행하려면 해당 게시물 끝에있는 링크를 확인하십시오.
(옵션 2)-robolectric-gradle-plugin을 사용하여 Android Studio에서 JUnit 테스트 실행
Android Studio의 gradle에서 실행할 junit 테스트를 설정하는 데 몇 가지 문제가 발생했습니다.
이것은 Android Studio의 gradle 기반 프로젝트에서 junit 테스트를 실행하기위한 매우 기본적인 샘플 프로젝트입니다. https://github.com/hanscappelle/android-studio-junit-robolectric Android Studio 0.8.14, JUnit 4.10에서 테스트되었습니다. robolectric gradle 플러그인 0.13+ 및 robolectric 2.3
빌드 스크립트 (project / build.gradle)
빌드 스크립트는 프로젝트의 루트에있는 build.gradle 파일입니다. 거기에 robolectric gradle 플러그인 을 classpath 에 추가 해야했습니다.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.13.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'org.robolectric:robolectric-gradle-plugin:0.13.+'
}
}
allprojects {
repositories {
jcenter()
}
}
프로젝트 빌드 스크립트 (App / build.gradle)
앱 모듈의 빌드 스크립트에서 robolectric플러그인을 사용하고 robolectric구성을 추가하고 androidTestCompile종속성을 추가 합니다.
apply plugin: 'com.android.application'
apply plugin: 'robolectric'
android {
// like any other project
}
robolectric {
// configure the set of classes for JUnit tests
include '**/*Test.class'
exclude '**/espresso/**/*.class'
// configure max heap size of the test JVM
maxHeapSize = '2048m'
// configure the test JVM arguments
jvmArgs '-XX:MaxPermSize=512m', '-XX:-UseSplitVerifier'
// configure whether failing tests should fail the build
ignoreFailures true
// use afterTest to listen to the test execution results
afterTest { descriptor, result ->
println "Executing test for {$descriptor.name} with result: ${result.resultType}"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile 'org.robolectric:robolectric:2.3'
androidTestCompile 'junit:junit:4.10'
}
JUnit 테스트 클래스 만들기
이제 테스트 클래스를 기본 위치에 넣습니다 (또는 gradle 구성 업데이트).
app/src/androidTest/java
Test로 끝나는 테스트 클래스의 이름을 지정하고 (또는 다시 구성 업데이트), junit.framework.TestCase테스트 메서드를 확장 하고 @Test.
package be.hcpl.android.mytestedapplication;
import junit.framework.TestCase;
import org.junit.Test;
public class MainActivityTest extends TestCase {
@Test
public void testThatSucceeds(){
// all OK
assert true;
}
@Test
public void testThatFails(){
// all NOK
assert false;
}
}
테스트 실행
다음으로 명령 줄에서 gradlew를 사용하여 테스트를 실행합니다 ( chmod +x필요한 경우 사용하여 실행 가능하게 만듭니다 ).
./gradlew clean test
샘플 출력 :
Executing test for {testThatSucceeds} with result: SUCCESS
Executing test for {testThatFails} with result: FAILURE
android.hcpl.be.mytestedapplication.MainActivityTest > testThatFails FAILED
java.lang.AssertionError at MainActivityTest.java:21
2 tests completed, 1 failed
There were failing tests. See the report at: file:///Users/hcpl/Development/git/MyTestedApplication/app/build/test-report/debug/index.html
:app:test
BUILD SUCCESSFUL
문제 해결
대체 소스 디렉토리
Java 소스 파일을 다른 곳에 둘 수있는 것처럼 테스트 소스 파일을 이동할 수 있습니다. gradle sourceSets구성을 업데이트하십시오 .
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
androidTest {
setRoot('tests')
}
}
org.junit 패키지가 없습니다.
앱 빌드 스크립트에 junit 테스트 종속성을 추가하는 것을 잊었습니다.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile 'org.robolectric:robolectric:2.3'
androidTestCompile 'junit:junit:4.10'
}
java.lang.RuntimeException : Stub!
명령 줄 (Android 스튜디오의 터미널 탭) 대신 Android 스튜디오의 실행 구성으로이 테스트를 실행하고 있습니다. Android Studio에서 실행하려면 app.iml하단에 jdk 항목이 나열 되도록 파일을 업데이트해야 합니다. 자세한 내용은 deckard-gradle 예제 를 참조하십시오.
전체 오류 예 :
!!! JUnit version 3.8 or later expected:
java.lang.RuntimeException: Stub!
at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
at junit.textui.TestRunner.<init>(TestRunner.java:54)
at junit.textui.TestRunner.<init>(TestRunner.java:48)
at junit.textui.TestRunner.<init>(TestRunner.java:41)
at com.intellij.rt.execution.junit.JUnitStarter.junitVersionChecks(JUnitStarter.java:190)
at com.intellij.rt.execution.junit.JUnitStarter.canWorkWithJUnitVersion(JUnitStarter.java:173)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
오류 : JAVA_HOME이 잘못된 디렉토리로 설정되었습니다.
해결책 은 이 SO 질문 을 참조하십시오 . bash 프로필에 아래 내보내기를 추가하십시오.
export JAVA_HOME=`/usr/libexec/java_home -v 1.7`
전체 오류 로그 :
ERROR: JAVA_HOME is set to an invalid directory: export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
테스트 클래스를 찾을 수 없습니다.
If you want to run your tests from Android Studio Junit Test runner instead you'll have to expand the build.gradle file a little more so that android studio can find your compiled test classes:
sourceSets {
testLocal {
java.srcDir file('src/test/java')
resources.srcDir file('src/test/resources')
}
}
android {
// tell Android studio that the instrumentTest source set is located in the unit test source set
sourceSets {
instrumentTest.setRoot('src/test')
}
}
dependencies {
// Dependencies for the `testLocal` task, make sure to list all your global dependencies here as well
testLocalCompile 'junit:junit:4.11'
testLocalCompile 'com.google.android:android:4.1.1.4'
testLocalCompile 'org.robolectric:robolectric:2.3'
// Android Studio doesn't recognize the `testLocal` task, so we define the same dependencies as above for instrumentTest
// which is Android Studio's test task
androidTestCompile 'junit:junit:4.11'
androidTestCompile 'com.google.android:android:4.1.1.4'
androidTestCompile 'org.robolectric:robolectric:2.3'
}
task localTest(type: Test, dependsOn: assemble) {
testClassesDir = sourceSets.testLocal.output.classesDir
android.sourceSets.main.java.srcDirs.each { dir ->
def buildDir = dir.getAbsolutePath().split('/')
buildDir = (buildDir[0..(buildDir.length - 4)] + ['build', 'classes', 'debug']).join('/')
sourceSets.testLocal.compileClasspath += files(buildDir)
sourceSets.testLocal.runtimeClasspath += files(buildDir)
}
classpath = sourceSets.testLocal.runtimeClasspath
}
check.dependsOn localTest
from: http://kostyay.name/android-studio-robolectric-gradle-getting-work/
Some more resources
The best articles I found around this are:
- http://tryge.com/2013/02/28/android-gradle-build/
- http://kostyay.name/android-studio-robolectric-gradle-getting-work/
- http://www.element84.com/easy-testing-with-android-studio.html
- http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Sourcesets-and-Dependencies
This is now supported in Android Studio starting with Android Gradle plugin 1.1.0, check this out:
https://developer.android.com/training/testing/unit-testing/local-unit-tests.html
Sample app with local unit tests on GitHub:
https://github.com/googlesamples/android-testing/tree/master/unittesting/BasicSample
For Android Studio 1.2+ setting up a project for JUnit is pretty simple try to follow along this tutorial:
This is the simplest part setting up a project for JUnit:
https://io2015codelabs.appspot.com/codelabs/android-studio-testing#1
Follow along the past link until "Running your tests"
Now if you want to integrate with intrumentation test follow along from here:
https://io2015codelabs.appspot.com/codelabs/android-studio-testing#6
Please see this tutorial from the Android Developers official site. This article also shows how to create mock-ups for your testing.
By the way, you should note that the scope of the dependencies for simple JUnit test should be "testCompile".
'Program Club' 카테고리의 다른 글
| Common Lisp를 실제로 사용하는 방법을 배울 수있는 곳 (0) | 2020.10.12 |
|---|---|
| JDK 8의 기본값은 Java의 다중 상속 형태입니까? (0) | 2020.10.12 |
| HTML5 기록 popstate에서 브라우저 스크롤 방지 (0) | 2020.10.12 |
| 변수를 사용하여 ggplot에서 열 이름을 지정하는 방법 (0) | 2020.10.11 |
| 웹 양식 내부에 부분보기를 포함하는 방법 (0) | 2020.10.11 |