gradle: compile android junit test apk file - java

Can I compile Android JUnit test apk file by using gradle script? Now my test class is:
public class main extends ActivityInstrumentationTestCase2<LoginWindow> {
public main() {
super("com.tecomgroup.handifox", LoginWindow.class);
}
...
}
and gradle says that he cannot find class LoginWindow. Should I add the LoginWindow.java to dependencies {} block? Will such test work? Or may be there is another way to compile test apk file?

When using Gradle Android plugin, you no longer need to have a separate project for testing. Production sources should be put into src/main/java directory, test sources should be in src/instrumentTest/java. The same applies to resources.
From Android Gradle plugin User Guide on project structure.
Project Structure
The basic build files above expect a default folder structure. Gradle follows the concept of convention over configuration, providing sensible default option values when possible.
The basic project starts with two components called “source sets”. The main source code and the test code. These live respectively in:
src/main/
src/instrumentTest/
Inside each of these folders exists folder for each source components.
For both the Java and Android plugin, the location of the Java source code and the Java resources:
java/
resources/
For the Android plugin, extra files and folders specific to Android:
AndroidManifest.xml
res/
assets/
aidl/
rs/
jni/
Note: src/instrumentTest/AndroidManifest.xml is not needed as it is created automatically.
You can change the standard project layout
sourceSets {
instrumentTest {
java {
srcDir '../other/src/java'
}
resources {
srcDir '../other/src/resources'
}
}
}

Related

How can you add dependency source code to sourceJar task output?

If you got a multi-project gradle build. And one module depends on another.
How could you add the dependency module source code to the output jar
Now i am using this:
java {
withSourcesJar()
}
I am new to gradle builds and i don't know any kotlin.
And if you have the source code of a dependency as a .jar file. Could you also add that
to the output?
So I have a project module:
dependencies:
project module
local .jar
What i want:
One .jar of the project (including other modules and dependencies) compiled code:
project-0.5.0.jar
..and one .jar of the source code (including other modules and dependencies)
project-0.5.0-sources.jar
I have all source code of dependencies stored locally as .jar files
Edit
My project conventions (global for all modules):
plugins {
`java-library`
}
java {
withSourcesJar()
}
How I am currently creating the project "fat".jar with compiled code:
(inside the build script)
tasks.jar {
//manifest.attributes["Main-Class"] = "com.example.MyMainClass"
val dependencies = configurations
.runtimeClasspath
.get()
.map(::zipTree) // OR .map { zipTree(it) }
from(dependencies)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
I have figured out how to add a project moduleA to another moduleB output sources .jar like so (inside moduleB's build-script):
tasks.sourcesJar {
from(project(":moduleA").sourceSets.main.get().allSource)
}
Now I need to figure out how to include source code from a dependency .jar
from(file("../path/dependency-1.0.0-sources.jar"))
This packs the .jar as it is. I need it's files.
I figured it out. And it was easier than i thought. Keep in mind i am using Kotlin.
(All code snippets are inside the build.gradle.kts file of the project / module you are creating the sources .jar for)
First off you need to include either the java or java-library plugin:
plugins {
`java-library`
}
And as far as i know, also this plugin extension:
java {
withSourcesJar()
}
This makes the sourcesJar task available (task used to create the sources jar), and you can modify it like so:
tasks.sourcesJar {
from(project(":common").sourceSets.main.get().allSource)
from(zipTree("../libs/tinylog-2.5.0/tinylog-api-2.5.0-sources.jar"))
}
The first line inside the brackets includes my "common" module source code to the output .jar.
The second line adds the .java files inside the tinylog sources .jar to the output .jar.

How to add source files to android studio project?

I currently try to get a huge Android Studio Project to compile. My problem is that I depend on java classes in a different git repo. I fixed it by adding the repo as a submodule. I'm an absolute newbie to gradle, so my approach was to add root, where the .java files are located as a a sourceset:
sourceSets {
main.java.srcDirs += '../../ROOT-OF-SOURCE-FILES/'
}
This resolves the dependencies. In "ROOT-OF-SOURCE-FILES" are a bunch of files not needed for my project and this also causes gradle not to build, because there are also no android files.
Next thing I tried is to point to the specific folders I depend on, but then it say "File path does not correspond to package name"
My question is how can I add the classes (including their dependencies) I need or how can I exclude the stuff I don't need (I also tried the exclude with gradle, but that didn't work).
You can use exclude to ignore parts of your source tree, see https://discuss.gradle.org/t/how-can-i-exclude-certain-java-files-from-being-compiled/5287:
sourceSets {
main {
java {
srcDirs 'main/src'
exclude '**/package2/**'
}
}
}
Another option is to create a symbolic link to the one branch that you really need for Android Studio, e.g.
src/main/
package1
package3
package2
linked/package1 -> src/main/package1
and
sourceSets {
main {
java {
srcDirs 'linked'
}
}
}

Choose Directory for Gradle Generated Source Code

I'm using Dagger 2 to generate some source code in my Gradle project. Right now those sources are being generated and added in the ./build/classes/main folder along with all the class files.
How do I choose a folder to separate all the generated .java files to?
How do I include that folder in my gradle Java project, and have IntelliJ view those as sources so I can use them in my project?
It looks like the application plugin only uses a certain set of directories by default, mixing in flavours of build to decide what files to compile.
However, I did find an example build script that creates a dagger configuration and manipulates gradle into using it for the generated output and adds it to the classpath. It uses dagger-compiler.
The core of it is:
sourceSets {
dagger {
java {
srcDirs = ['src/dagger/java']
}
}
}
configurations {
compileDagger
}
compileJava {
description = "dagger annotation processor is loaded automatically from classpath"
sourceSets.dagger.java.srcDirs*.mkdirs()
classpath += configurations.compileDagger
options.compilerArgs += [
'-s', sourceSets.dagger.java.srcDirs.iterator().next()
]
}
clean {
description = "delete files in generated source directory tree"
delete fileTree(dir: sourceSets.dagger.java.srcDirs.iterator().next())
}
dependencies {
ext.daggerVersion = "2.0.1"
compile(
"com.google.dagger:dagger:${daggerVersion}",
"com.google.guava:guava:18.0")
compileDagger(
"com.google.dagger:dagger-compiler:${daggerVersion}")
}
Regarding IntelliJ, the plugin should automatically add any srcSets via the normal building of the idea project, so there should be no additional configuration needed, just regenerate it.

Using Gradle with native dependencies

I am trying to use Sigar in a Gradle project. Sigar distribution is by default provided with 2 types of files:
a JAR that contains classes
some native files (.so, dylib, .dll)
My purpose is to repackage these files so that I can use them as dependencies deployed and downloaded on-demand from a personal Maven repository.
My first try was to define dependencies as files in order to check that my application is working as expected before to repackage. Below is the Gradle code I used for my first test that works:
dependencies {
compile files("${rootDir}/lib/sigar/sigar.jar")
runtime fileTree(dir: "${rootDir}/lib/sigar/", exclude: "*.jar")
}
Then, I have repackaged Sigar native files into a JAR and renamed the other one to match rules for maven artifacts since I want to deploy them in a Maven repository. Below is what I get:
sigar-1.6.4.jar (contains .class files)
sigar-1.6.4-native.jar (contains .dylib, .so, and .dll files at the root)
The next step was to deploy these files in my custom repository. Then, I have updated my build.gradle as follows:
dependencies {
compile 'sigar:sigar:1.6.4'
runtime 'sigar:sigar:1.6.4:native'
}
Unfortunately, when I do a gradle clean build, new dependencies are fetched but native libraries can no longer be found at runtime since now I get the following exception:
Error thrown in postRegister method: rethrowing <java.lang.UnsatisfiedLinkError: org.hyperic.sigar.Sigar.getCpuInfoList()[Lorg/hyperic/sigar/CpuInfo;>
Consequently, I am looking for a solution to fetch and to link native files to my Java app like for other dependencies. Any advice, comment, suggestion, help, solution, etc. are welcome ;)
A solution is to define a new gradle configuration that unzips JAR files at the desired location:
project.ext.set('nativeLibsDir', "$buildDir/libs/natives")
configurations {
nativeBundle
}
dependencies {
nativeBundle 'sigar:sigar:1.6.4:native'
}
task extractNativeBundle(type: Sync) {
from {
configurations.nativeBundle.collect { zipTree(it) }
}
into file(project.nativeLibsDir)
}
dist.dependsOn extractNativeBundle
Then, this location must be put in java.library.path for tasks that depend on native libraries:
systemProperty "java.library.path", project.nativeLibsDir

How do I create an Android Test Module in IntelliJ 13 for a Gradle Android project?

I have successfully create a Android project in IntelliJ 13 and I want to setup the Android Testing Framework. I used the new project wizard to create the android project using Gradle. When I go to add a new module I only have options for "Gradle: Android Module" and "Gradle: Java Library", the "Test Module" option is missing.
How do I generate an Android Test Module? I have read http://www.jetbrains.com/idea/webhelp/testing-android-applications.html but I can never find any "test" option.
If an Android Test Module can not be automatically generated, then how do I configure and use the Android Testing Framework with a Gradle Android Project? Links to examples or documentation is very much appreciated.
Details: IntelliJ 13.1.3
So currently your directory structure should look something like this:
ProjectDirectory/
res/
src/
main/
java/
your.package.name
MyClass.java
All you need to do is add a src directory for androidTest:
ProjectDirectory/
res/
src/
main/
java/
your.package.name
MyClass.java
androidTest/
java/
your.package.name
MyClassTest.java
and then resync your Gradle file with your project, and it should be detected as a test directory. Then you can run the connectedCheck or connectedAndroidTest tasks (I'm unclear on the difference in the two) to run the tests.
If your directory structure differs from the above (if, for instance, you important an Eclipse-style project), you can specify the alternate src directory in your build.gradle script:
android {
sourceSets {
androidTest {
java.srcDirs = ['path/to/test/src']
}
}
}
As an alternative You could try switching to Android Studio, Its built on top of ItelliJ. If you are creating a new project Android Studio creates the test directory automatically for you.
After a lot of tries I've found the way that's definitively good:
Create a test folder under your package.
Create a class (call it ExampleTest would be good) extending InstrumentationTestCase into this folder.
Lets add a simple test which we know will fail:
public class ExampleTest extends InstrumentationTestCase {
public void test() throws Exception {
final int expected = 1;
final int reality = 5;
assertEquals(expected, reality);
}
}
Remeber that all test methods MUST start with the “test-” prefix or Android Studio will not detect them as tests and you will get all kinds of weird errors and nothing will work.
Now that we have a test case which is doomed for failure, we must now run it.
Start by clicking “Run -> Edit Configurations.”
Now select “+ -> Android Tests” from the upper left hand corner and select “Android Tests” and name your new test configuration “test” or something equally relevant.
Select your current module and next select the “All in Package” option and navigate to your “test” folder you just created. You can also select “All in Module” and Android Studio will automatically find any test inside your whole Module! You can also get more specific and select “Class” or even “Method” option to narrow the scope of your testing down further.
Apply, close, and run this configuration! The test will run..!
Information are taken by this link:
http://rexstjohn.com/unit-testing-with-android-studio/
It's written for android studio, but it work for intelliJ 13 too! ;)
have fun!
I've had trouble with creating android projects in Intellij, so now I create projects in Eclipse and then import them into Intellij. It's annoying, but it's an easy fix and it works.

Categories

Resources