how to create test class and folder from android studio? - java

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.

Related

Separate ServiceProviders for Unit Testing and Production Code

I am using ServiceLoader to dynamically load Plugins.
In purpose of unit testing I want to Mock some behavior of these Plugins.
These Mock-Plugins should be used when unit testing, but not when building the Project.
How would one do this though?
I feel like this question is IDE / build tool specific, for that matter I am using Eclipse.
Project Structure:
src
app
app.java
scraper
ScraperController.java
Scraper.java
Scrapers
tests
mockups
FailingScraperMock.jar
...
unit_tests
ServiceLoaderWithProvidedMockScrapersTest.java
...
scraper.Scraper.java is the provider interface
Scrapers is where all the Scraper-Providers go
I tried to exclude the Mock-Plugins for the source folder: src/ .
Either I am doing it wrong or that's not intended for what I am trying to do.
Would appreciate any kind of help / information.
If you mark your test folder (/tests) as test code and then it should be excluded from application builds.

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

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

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

Java/Eclipse: How to configure Run Configuration's Classpath for JUnit test?

I have an Eclipse project with the following directory structure:
MyProj/
src/main/java/
com.me.myproject.widgets
Widget.java
src/main/config
widget-config.xml
src/test/java
com.me.myproject.widgets
WidgetTest.java
src/test/config
widget-test-config.xml
The Widget class reads its config (XML) file in from anywhere on the classpath and uses it to configure its properties.
I am trying to just get WidgetTest's test cases (all written with JUnit) to run inside Eclipse when I right-click the file and go to Run As >> JUnit Test. I assume I'll have to actually run it as a customized Run Configuration with its own configured classpath, but I'm not sure about that as I've never done this before.
Does anybody know how I can get a custom Run Configuration to run WidgetTest.java as a JUnit test, and successfully place src/test/config/widget-test-config.xml on the classpath? Thanks in advance!
Please note, this question is not about how to read a resource from the runtime classpath, its about how to get it on Eclipse's JUnit Run Config classpath in the first place!
I was under the impression that as long as you have src/test/config/widget-test-config.xml inside what Eclipse considers to be a source folder, it should already be on the classpath.
Is src/test a source folder for Eclipse ? If it is and you still get the problem, try out the following experiment :
If you copy widget-test-config.xml to the src root can Widget class read it ?
If Yes
then it's a problem of the test folder not being on the classpath and you may wanna try adding it manually like so.
Right click WidgetTest and select Run As -> Junit Test. This should automatically create a Junit Run Configuration accessible at Run -> Run Configurations. You modify it's Classpath entry to add the project containing the .xml file like so :
If No
If, even after moving the .xml file to the src root (i.e. default package), your widget class cannot read it then there is something else wrong. In that case, it would be great if you could furnish the snippet of code in WidgetTest which is trying to read the .xml file.
Working Code
Here is a bit of working code :
public class A {
#Test
public void test() {
InputStream stream = A.class.getResourceAsStream("/SomeTextFile.txt");
System.out.println(stream != null);
stream = Test.class.getClassLoader()
.getResourceAsStream("SomeTextFile.txt");
System.out.println(stream != null);
}
}
The above works for me in a simple JAVA project and runs fine. (Running fine means getting
'true' printed on the console)
I am in the process of creating a GITHub repo for you to try out this code painlessly.
GIT Hub Repo with Test project
You should be able to import the project in this zip and see the code working. Right click on the Test class A and click Run As -> Junit Test, and you should see two true in the Console.
If your WidgetTest class is written as a JUnit test, eclipse will try to run it as a Junit test automatically. If it doesn't, you should right click on the class in the package explorer, choose Run As >> Run Configuration >> choose Junit
To run a Junit test:
in JUnit3, the class should implement TestCase and all the method names should start "test"
in JUnit4, all the methods should be preceded by a #Test annotation
To place that config file in the classpath: when setting the Run Configuration as above, go to the Arguments tab in the upper right pane and in the VM arguments specify the classpath:
-cp .:/path/to/the/config/file
However, if that file is in a package in the source directory, it should automatically be included in the classpath.

Gradle - how to run the tests from a different gradle project and still get coverage data

Does anyone know how to run the tests from a different gradle project and still get emma coverage reporting data?
Here is my current layout:
Root/
settings.gradle (no explicit build.gradle - just defines all subprojects)
SubProjectA/
build.gradle
src/ (all real source is here)
SubProjectATest/
build.gradle
src/ (all testing code is here)
SubProjectB/ (similar structure as A)
SubProjectBTest/ (similar structure as ATest)
I am currently using the emma plugin, and I would like to build SubProjectA and run all the tests in SubProjectATest from within the build.gradle of SubProjectA.
Here are some things I tried inside the build.gradle of SubProjectA
testCompile project(':SubProjectATest').sourceSets.test.classes (as suggested by this article), but I got an error "Could not find property 'sourceSets' on project"
Just the straight-up testCompile project(':SubProjectATest'), but then I get "..SubProjectA/build/classes/test', not found" and also "Skipping task ':SubProjectA:compileTestJava' as it has no source files."
Simply adding a sourceSet like the following:
test {
java {
srcDir '../SubProjectATest/src'
}
}
Adding the source set in (option 3) is the only option that worked, but it seems sloppy to do it this way. Does anyone know how to do this using project dependencies?
Update #1
I also tried one of the answers below to use test.dependsOn and the tests do run, but the emma plugin reported the following: build/classes/test', not found
1. and 2. just add classes to the test compile class path. This doesn't have any effect on which tests are going to be executed.
3. is the wrong approach because you should not add sources from project X to project Y.
If what you want is that gradle :SubProjectA:test also executes :SubProjectATest:test, all you need to do is to add a task dependency:
SubProjectA/build.gradle:
test.dependsOn(":subProjectATest:test")
By the way, what is your motivation for putting the tests in a separate project?

Categories