Git Product home page Git Product logo

androidstudioandrobolectric's Introduction

AndroidStudioAndRobolectric

Get Started on command-line

  1. Just clone.
  2. Go into the project directory.
  3. Run ./gradlew test and get started with robolectric.

Get Started with Android Studio

  1. Import this project with Android Studio.
  2. Change the Build Variant // Test Artifact to Unit Test (http://tools.android.com/tech-docs/unit-testing-support).
  3. Right click on a test and get started with robolectric.

More example project setups

Flavors

Here an example with flavors https://github.com/nenick/AndroidStudioAndRobolectric/tree/flavors

Multi Modules (Android Library)

Here an example with android library module https://github.com/nenick/AndroidStudioAndRobolectric/tree/library

Library depends on other android libraries

Here a special example when the library has aar dependencies https://github.com/nenick/AndroidStudioAndRobolectric/tree/library-with-aar

Separate Test Module

For some use cases it is great to split tests into different modules https://github.com/nenick/android-gradle-template

"THE BEER-WARE LICENSE": As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. Nico Küchler

androidstudioandrobolectric's People

Contributors

jaredsburrows avatar nenick avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

androidstudioandrobolectric's Issues

Test is stuck at :app:testDebug

Hi,

I checked out the source code and run this command ./gradlew clean test. It's stuck at

:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:compileDebugJava
:app:preCompileDebugUnitTestJava
:app:compileDebugUnitTestJava
:app:compileDebugUnitTestSources
:app:mockableAndroidJar
:app:assembleDebugUnitTest
> Building 54% > :app:testDebug

Do you have any idea how can I resolve this issue?

Thanks!
Henry

Not An Issue

This is not an issue. But I would love to buy you a coffee! I've been banging my head for the past 4 weeks on setting up test suites for library based projects without Activity's. I just got my first passing test case thanks to your repository! :D (Not joking about the coffee, its the least I could do!)

Fails with org.robolectric:robolectric:3.0-rc3

When updating to the latest RC for Robolectric 3.0, the tests no longer work, but lead to the following error:

java.lang.RuntimeException: /Users/mtotschnig/entwicklung/AndroidStudioAndRobolectric/app/build/intermediates/bundles/debug/res/values is not a directory
    at org.robolectric.res.DocumentLoader.load(DocumentLoader.java:27)
    at org.robolectric.res.PackageResourceLoader.loadEverything(PackageResourceLoader.java:32)
    at org.robolectric.res.PackageResourceLoader.doInitialize(PackageResourceLoader.java:19)
    at org.robolectric.res.XResourceLoader.initialize(XResourceLoader.java:29)
    at org.robolectric.res.OverlayResourceLoader.doInitialize(OverlayResourceLoader.java:22)
    at org.robolectric.res.XResourceLoader.initialize(XResourceLoader.java:29)
    at org.robolectric.res.XResourceLoader.getValue(XResourceLoader.java:52)
    at org.robolectric.res.OverlayResourceLoader.getValue(OverlayResourceLoader.java:51)
    at org.robolectric.res.RoutingResourceLoader.getValue(RoutingResourceLoader.java:31)
    at org.robolectric.shadows.ShadowAssetManager.getAndResolve(ShadowAssetManager.java:353)
    at org.robolectric.shadows.ShadowAssetManager.getAndResolve(ShadowAssetManager.java:349)
    at org.robolectric.shadows.ShadowAssetManager.getResourceText(ShadowAssetManager.java:67)
    at android.content.res.AssetManager.getResourceText(AssetManager.java)
    at android.content.res.Resources.getText(Resources.java:270)
    at org.robolectric.shadows.ShadowResources.getText(ShadowResources.java:358)
    at android.content.res.Resources.getText(Resources.java)
    at android.content.res.Resources.getString(Resources.java:360)
    at org.robolectric.shadows.ShadowContext.getString(ShadowContext.java:33)
    at org.robolectric.shadows.ShadowContextWrapper.getString(ShadowContextWrapper.java:78)
    at android.content.Context.getString(Context.java)
    at org.robolectric.util.ActivityController.getActivityTitle(ActivityController.java:108)
    at org.robolectric.util.ActivityController.attach(ActivityController.java:49)
    at org.robolectric.util.ActivityController$1.run(ActivityController.java:121)
    at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:305)
    at org.robolectric.shadows.CoreShadowsAdapter$2.runPaused(CoreShadowsAdapter.java:45)
    at org.robolectric.util.ActivityController.create(ActivityController.java:118)
    at org.robolectric.util.ActivityController.create(ActivityController.java:129)
    at org.robolectric.util.ActivityController.setup(ActivityController.java:210)
    at org.robolectric.Robolectric.setupActivity(Robolectric.java:46)
    at com.example.myapplication.RobolectricTest.testIt(RobolectricTest.java:16)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:245)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:185)
    at org.robolectric.RobolectricTestRunner.runChild(RobolectricTestRunner.java:54)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:149)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
´´´

Can't run Roboletric on windows: java.lang.NoSuchMethodException: android.os.Looper.<init>(boolean)

I don't know if this issue happens only at windows, but as I just run the the project as it is, and got the issue plus, no other related issue was filed, I guess it could be.

I just ran RobolectricTest (right click) and got:

 java.lang.RuntimeException: java.lang.NoSuchMethodException: android.os.Looper.<init>(boolean)
    at org.robolectric.util.ReflectionHelpers.callConstructor(ReflectionHelpers.java:233)
    at org.robolectric.shadows.ShadowLooper.createLooper(ShadowLooper.java:43)
    at org.robolectric.shadows.ShadowLooper.access$000(ShadowLooper.java:25)
    at org.robolectric.shadows.ShadowLooper$1.create(ShadowLooper.java:37) ... 

@Config and @RobolectricTestRunner not recognised

I came from stackoverflow.com question.(http://stackoverflow.com/questions/29714750/android-studio-1-1-0-cannot-setup-robolectric).
Thanks for your answer but I have cloned your project and tested your code, but Android Studio cannot recognise @config and @RobolectricTestRunner annotations when I added @config(emulateSdk = 18)
@RunWith(value = RobolectricTestRunner.class) in the ApplicationTest class.
Please let me know how I fix the issue.

import android.app.Application;
import android.test.ApplicationTestCase;

import org.junit.runner.RunWith;

/**
 * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
 */
@Config(emulateSdk = 18)
@RunWith(value = RobolectricTestRunner.class)
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}

Support for running unit tests in parallel

Use of android-unit-test plugin allows for configuring the number of forks to use during test execution, as does having a vanilla java module within the project to host the unit tests. This is typically achieved by configuring a 'maxParallelForks' value in the build scripts.

Such configuration has allowed my test suite to complete in ~3.5 mins. Without it, it takes over 10 mins.

A way to configure an equivalent to 'maxParallelForks' using this setup would definitely be appreciated.

No Copyright/License Information

Firstly, really appreciate this great starter project. Was it not intended for open source use? I did not see any copyright information.

Resources not found exception when applicationId is altered

Running Robolectric tests fail with a android.content.res.Resources$NotFoundException when in build.gradle the applicationId is changed.

The exception happens when applicationId is set in defaultConfig or a build flavor to a value different than the one in the AndroidManifest. Same thing happens when applicationIdSuffix is used.

No issue ( java.lang.StringIndexOutOfBoundsException: String index out of range: -9)

I added a very simple activity with a very simple layout and i get following exception when running the test.

java.lang.StringIndexOutOfBoundsException: String index out of range: -9
at java.lang.String.substring(String.java:1954)
at org.robolectric.res.ResName.qualifyResName(ResName.java:51)
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getParent(ShadowAssetManager.java:466)
at org.robolectric.shadows.ShadowAssetManager$StyleResolver.getAttrValue(ShadowAssetManager.java:415)
at org.robolectric.shadows.ShadowResources.getOverlayedThemeValue(ShadowResources.java:295)
at org.robolectric.shadows.ShadowResources.attrsToTypedArray(ShadowResources.java:134)
at org.robolectric.shadows.ShadowResources.access$000(ShadowResources.java:51)
at org.robolectric.shadows.ShadowResources$ShadowTheme.obtainStyledAttributes(ShadowResources.java:489)
at android.content.res.Resources$Theme.obtainStyledAttributes(Resources.java)
at android.content.Context.obtainStyledAttributes(Context.java:472)
at android.view.View.__constructor__(View.java:3677)
at android.view.View.<init>(View.java)

The layout is very simple (empty).

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/myId"/>
</LinearLayout>

The Test is only creating the activity.

@RunWith(CustomTestRunner.class)
@Config(constants = BuildConfig.class)
public class TestSimpleActivity
{
 @Test
public void test()
{
    SimpleActivity activity =  Robolectric.buildActivity(SimpleActivity.class).create().start().resume().visible().get();

    Assert.assertEquals(true, "test".equals("fail"));
}
}

Any ideas or suggestions?

NoClassDefFoundError OnApplyWindowInsetsListener

When I have the issue java.lang.NoClassDefFoundError: android/support/v4/view/OnApplyWindowInsetsListener then it helped me to do a gradle refresh and close the current project at Android Studio and reopen the project at the project selection window.

java.lang.RuntimeException: java.lang.ClassNotFoundException: android.app.Application

When I try to run your library example and want to execute the RobolectricCoreTest I get this exception:

java.lang.RuntimeException: java.lang.ClassNotFoundException: android.app.Application
at org.robolectric.annotation.Config$Implementation.parseApplication(Config.java:123)
at org.robolectric.annotation.Config$Implementation.fromProperties(Config.java:92)
at com.example.core.CustomRobolectricRunner.overwriteConfig(CustomRobolectricRunner.java:37)
at com.example.core.CustomRobolectricRunner.getAppManifest(CustomRobolectricRunner.java:29)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:182)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.RobolectricTestRunner$1.evaluate(RobolectricTestRunner.java:158)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: java.lang.ClassNotFoundException: android.app.Application
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at org.robolectric.annotation.Config$Implementation.parseApplication(Config.java:120)
... 23 more

Is there any way that I can fix that one? Basically every Unit Test class works except for RobolectricCoreTest

Adding android.sourceSets.test.java.srcDirs += "build/generated/source/r/debug" worked for the R. issue.

Gradle DSL method not found: 'execute()'. Any solution?

FAILURE: Build failed with an exception.

Where:
Script '/Users/la20073037/AndroidStudioProjects/Telstra_24x7/telstra-24x7-android/app/buildscripts/copy_test_resources.gradle' line: 32

What went wrong:
Could not find method execute() for arguments [] on task ':app:copyTestSqiObfuscatedReleaseResources' of type org.gradle.api.tasks.Copy.

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.4.1/userguide/command_line_interface.html#sec:command_line_warnings

Code:

gradle.projectsEvaluated {
// Base path which is recognized by android studio.
def testClassesPath = "${buildDir}/intermediates/classes/test/"
// Copy must be done for each variant.
def variants = android.applicationVariants.collect()

variants.each { variant ->
    def variationName = variant.name.capitalize()

    // Get the flavor and also merge flavor groups.
    def productFlavorNames = variant.productFlavors.collect { it.name.capitalize() }
    if (productFlavorNames.isEmpty()) {
        productFlavorNames = [""]
    }
    productFlavorNames = productFlavorNames.join('')

    // Base path addition for this specific variant.
    def variationPath = variant.buildType.name;
    if (productFlavorNames != null && !productFlavorNames.isEmpty()) {
        variationPath = uncapitalize(productFlavorNames) + "/${variationPath}"
    }

    // Specific copy task for each variant
    def copyTestResourcesTask = project.tasks.create("copyTest${variationName}Resources", Copy)
    copyTestResourcesTask.from("${projectDir}/src/test/resources")
    copyTestResourcesTask.into("${testClassesPath}/${variationPath}")
    copyTestResourcesTask.execute()
}

}

def uncapitalize(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return str;
}
return new StringBuffer(strLen)
.append(Character.toLowerCase(str.charAt(0)))
.append(str.substring(1))
.toString();
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.