How to run a simple JUnit4 test in Android Studio 1.1? - java

I have an Android project that shows "Hello World". It was created from the "Blank Activity" template from Android Studio.
I then add/create a new java class in my application package (the same package that has my activity). I call it Shape and add a simple constructor
public class Shape {
public Shape(int i){
if (i==0){
throw new IllegalArgumentException("Cant have 0");
}
}
}
Great. Now I have a class that isn't touching Android at all, and I want to unit test it. What should I do next?
This is where my question stops. Below I'll go through what I tried.
Please note that I really have never tested before in Android or Java. Excuse me for "rookie" mistakes.
While in the Shape.java I go to "Navigate" > "Test"
Hit enter to select "Create new Test"
Get this popup, and select JUNIT4.
I then hit the fix button to fix the library not being found
I get this popup
I'm not really sure what to select, so I select the default/highlighted.
I write my test
package com.eghdk.getjunit4towork;
import org.junit.Test;
import static org.junit.Assert.*;
public class ShapeTest {
#Test(expected = IllegalArgumentException.class)
public void testShapeWithInvalidArg() {
new Shape(0);
}
}
At this point, I'm not really sure how to run my tests, but try to do this:
I get these errors when running
Error:(3, 17) Gradle: error: package org.junit does not exist
Error:(5, 24) Gradle: error: package org.junit does not exist
Error:(8, 6) Gradle: error: cannot find symbol class Test

Since Android Studio 1.1, there is (experimental) unit test support. A couple of quotes from that page:
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"
}
To use unit testing support in AS, you have to do the following steps:
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 (see above).
Enable the unit testing feature in Settings > Gradle > Experimental.
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.
Create your test. You can do this by opening a class, right-clicking its name and selecting "Go to > Test". Add some test
cases.
Right click your new test class or method and select "Run ...".
(Optional) You can decrease the compilation time by using Gradle directly. To do this, go to the Run menu and select "Edit
configurations". There, find the default JUnit template, remove the
"Make" before-launch step and add a "Gradle aware make" step instead
(leave the task name empty).
It is important to know that there are two test types: androidTest and plain test.
androidTest is primarily for tests you run on an emulator or device, such as instrumentation tests. From the command line, you use ./gradlew connectedCheck to run these.
test is for tests you don't want to run on a device, such as the unit test you wrote. You run ./gradlew test to run these tests.
As stated in the quote, you switch between androidTest and test in Android Studio by changing the test artifact.
Naturally, it is preferred to not run tests on a device or emulator, since this speeds up the testing process a lot. With the new experimental unit test support, you gain access to stubbed Android API's without using a device. This lets you move more tests from androidTest to test.

For android studio 1.2 or greater, I include this answer since this is one of the first ranking at google and this is an excelent and VERY easy to follow tutorial on how to set unit tests with Android Studio, this is the link: https://io2015codelabs.appspot.com/codelabs/android-studio-testing#1
After wasting 2 hours trying to run test I finally did it with the above link, hope it is as useful for you as for me.

Nowadays Android Studio (current ver. 1.4) has full Unit test support without any workarounds. Just as suggested in the automatically generated ExampleUnitTest:
To work on unit tests, switch the Test Artifact in the Build Variants view.

Go to settings then build tools then gradle and then experimental. In experimental uncheck enable all test artifacts. Thats it game over

Related

Test is not exclude using EnabledOnOs/DisabledOnOs tag using Junit 5, Java 11

I am playing around with Junit 5 (conditional skip) and jdk-11.01 to ignore some tests for the first time. I do not manage to get the #Disable/#Enable to disable testcases. Please share any ideas how to get this to work?
Example:
#DisabledOnOs(OS.LINUX)
#EnableOnOs(OS.WINDOWS)
#DisabledForJreRange
https://www.baeldung.com/junit-5-conditional-test-execution
The only exclusion that still works are the #Ignore flag.
I have tested to run a test suite from "GitHub Actions" or locally from IntelliJ with the Junit 5 plugin, and the tests are still executed even though the condition is met (example running a test on Linux machine) when test is marked #EnableOnOs(OS.WINDOWS)!
Example test:
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
...
#EnabledOnOs(OS.WINDOWS)
#Test
public void onlyRunOnWindowsTest() {
log.info("Test run on Windows env. only");
// more test code ...
}
Is there anything else I need to configure the test with in order to have this working?
I also have this:
from dependencis in gradle.build I have:
// https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.7.0'
in project External Libraries (intelliJ) I have:
> Gradle:junit:junit:4.1
I tried to remove this junit 4.1 (if there were due to conflict reasons), from project but this popped up again directly from a Gradle refresh. I guess junit5 uses this jar.
> Gradle:org.junit.jupiter:junit-jupiter-api:5.7.0
Yes, this is definitely a Junit 4 vs Junit 5 migration that went wrong. The following steps helped me get this to work.
If you are working with huge project this auto correction is most welcome (converting all tags and assertions to junit5 syntax automatically):
https://github.com/junit-pioneer/convert-junit4-to-junit5
Then you might also need to fix some project problems described in this post:
No tests found for given includes Error, when running Parameterized Unit test in Android Studio
Good luck!

how to create test class and folder from android studio?

I want to build unit test from existing android project but the test folder and test class like androidTest and test are deleted. Because this is existing project and I dont know why previous developer deleted them, so I need to create new test folder for this to work.
I try add the libraries to my gradle like this :
// Required -- JUnit 4 framework
testCompile 'junit:junit:4.12'
// Optional -- Mockito framework
testCompile 'org.mockito:mockito-core:1.10.19'
and create test folder and the test class inside src folder but still not works and I can't run the test.
any idea what the correct steps to achieve this in android studio? since the documentation only showing how to add the test library and the test class but not where to place test folder or create new test folder.
You can 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.
Also make sure to choose the correct build variant.
For more details on how to configure all this and run the tests properly, please refer http://tools.android.com/tech-docs/unit-testing-support
Hope this helps.

Unable to run JUnit test in IntelliJ

I wanted to start project using TDD. Created the test directory and later changed it to package that is integrated with src direcotry. In both cases I get the same error:
Class not found: "tests.objectsTest"
I tried different techniques of importing JUnit jar and none solved problem. Also I tried to rename my test class but it gives no solutons whatsoever.
It seems that IntelliJ or JUnit changes name of the test class. Shouldn't it be objectsTest.tests?
I am using JUnit version 4.12 and latest IntelliJ EAP.
This is my project structure:
Project:
-.idea
-src
-logic
-objects
-tests
-test
-test.java
src and tests are directories marked as Source and Test. Every package except test is empty. On my other PC with IntelliJ Community Edition everything works fine but on EAP there is this bug. Unfortunatelly I have to use EAP.
test.java code:
package test;
import org.junit.Test;
public class test {
#Test
public void canCreateInhabitant(){
}
}
Have you checked if you have the JUnit plugin enabled? I (foolishly, shame!) disabled it at some point and was unable to get IDEA to run my tests until I remembered to turn the plugin back on...
Check the root directory of your classes. It must be marked as source (for java classes) or test (for java test classes).
It seems that your directory is not well marked in IntelliJ.
I did a simple test and put it on github.
It's the absolute simplest of tests but it works great, standing inside the test class pressing shift+ctrl+t will run the test.
Go ahead and clone it and try it out.
Easiest way is:
Open Class in Intellij and press Ctrl+Shift+T
Select "Create New Test"
Now, a new pop up will be opened where you can select Unit Test Library (For your case its Junit4)
Select the methods which you want to include in test
And there you go !
Sometimes I find that this happens when I try and launch "All tests" from the project folder in the structure view. Launching all tests by right clicking on the test root folder and selecting "all tests" from there seems to solve it.
Just had this happen to me. When I built via Maven it had a problem. When I fixed the problem, it would run the junits again. Goofy.
I had the same problem, I solved it by clicking File-> Invalidate chaces and Invalidate an Restart

java.lang.NoClassDefFoundError while running JUnit test in Netbeans

I am building an Android hello world application in Netbeans. It's building properly and I am able to run in the emulator also.
But when creating and running the Junit test I get a java.lang.NoClassDefFoundError.
How can I fix this problem?
Check the manifest of your test project, for example HelloWorldTest/AndroidManifest.xml. The android:targetPackage attribute of the instrumentation markup should target the package in your application, for example, com.example.helloworld. Not the test package of your test project (eg. com.example.helloworld.test).
Simply AndroidManifest.xml -> manifest -> package of main application should match AndroidManifest.xml -> manifest -> instrumentation -> android:targetPackage of the test application.
The full error message contains the name of the class, that wasn't found on the classpath. Double check if the classpath that is used for running the test includes all required classes and libraries (your class files, junit.jar, android specific libaries).
I find that a rebuild usually finds the classes (as it is a classpath issue). Netbeans seems to aggressively compile existing tests, but the main source code (from a maven setting at least) is not always available.
I've started running full builds to try address this. There might be a plugin that addresses this but I haven't found it yet.
EDIT: This might help.
I don't know about netbeans specifics, but the problem is probably the same.
FragmentActivity can not be tested via ActivityInstrumentationTestCase2
Your test project can be using a different android compatibility library than your main project, and that causes this weird errors.

JUnit4 in Eclipse

I'm trying to run some JUnit test units in Eclipse 3.5, but with no luck at all.
JUnit3 works fine.
When I create the JUnit4 Test unit, Eclipse offers to add the JUnit library to the class-path. I accept, but when I check to see if it was added in the project's properties panel, I can see JUnit4 was added, but no JARS where included.
If I choose Edit, the combo says "JUnit 4", and just below "Current location: Not Found".
When I launch a JUnit4 test, I get an error saying and internal error occurred, NullPointerException.
I've read for about two days now, and all references say eclipse INCLUDES JUnit4, but somehow, there seems to be something I'm missing.
I've tried re-creating my projects and creating a test in brand new ones with no luck.
package test;
import static org.junit.Assert.*;
import org.junit.Test;
public class AuthServiceTest {
#Test
public final void testValidateCredentials() {
fail("Not yet implemented"); // TODO
}
}
[Edit]
I've added junit-4.8.1.jar to the project's classpath, and eclipse's classpath, but still the same problem.
[Edit2]
I also added junit-dep-4.8.1.jar, since I'm not sure if these dependencies are necessary, but no change.
Right click on the project name .
Built Path--> Add Libraries
Select the appropriate library from the list (JUnit 4 in this instance) .
In my Eclipse installation JUnit 4 is provided, it's in plugins\org.junit4_4.3.1\junit.jar
If you can't find it, then I guess that you may need to download it.
You can associate your JUnit with the Eclipse JUnit settings in
Windows->Preferences->Java->Build Path->User Libraries
Select JUnit there, and you can add and edit JARs.
It appears that the Eclipse 3.5 from Fedora's repository doesn't include JUnit, and installing the appropriate package didn't include it either.
Another Debian PC presented the same issue. A clean download from eclipse.org solved the problem.
I will report this bug at some point :)

Categories