A set of AssertJ helpers geared toward testing Android.

Overview

AssertJ Android

A set of AssertJ assertions geared toward testing Android.

Deprecated

The support libraries and play services are developing at a rate which this library cannot sustain. Additionally, we no longer think AssertJ's model for supporting alternate assertions is a good practice.

We recommend using Truth which has vastly superior extensibility model which, when coupled with things like Kotlin's apply method create a really nice assertion experience.


Writing tests is not the most glamorous part of developing an Android application but it is an invaluable one. Using libraries like JUnit and AssertJ provide a great starting point for writing tests.

This library is an extension of AssertJ which aims to make it even easier to test Android.

Examples

  • AssertJ Android:

    assertThat(view).isGone();
  • Regular JUnit:

    assertEquals(View.GONE, view.getVisibility());
  • Regular AssertJ:

    assertThat(view.getVisibility()).isEqualTo(View.GONE);

When failing, the AssertJ Android assertion produces an output which allows you to immediately recognize the problem: Expected visibility <gone> but was <invisible>.

Compare that to the output of regular AssertJ Expected:<[8]> but was:<[4]> and regular JUnit Expected: <8> but was: <4> and you should immediately see the advantage.

Because AssertJ Android offers assertions directly on objects rather than properties they can be chained together.

  • AssertJ Android:

    assertThat(layout).isVisible()
        .isVertical()
        .hasChildCount(4)
        .hasShowDividers(SHOW_DIVIDERS_MIDDLE);
  • Regular JUnit:

    assertEquals(View.VISIBLE, layout.getVisibility());
    assertEquals(VERTICAL, layout.getOrientation());
    assertEquals(4, layout.getChildCount());
    assertEquals(SHOW_DIVIDERS_MIDDLE, layout.getShowDividers());
  • Regular AssertJ:

    assertThat(layout.getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(layout.getOrientation()).isEqualTo(VERTICAL);
    assertThat(layout.getChildCount()).isEqualTo(4);
    assertThat(layout.getShowDividers()).isEqualTo(SHOW_DIVIDERS_MIDDLE);

Assertions exist for nearly every object that you would ever want to test, from LinearLayout to ActionBar to Fragment to MenuItem. Everything in the support library is included too.

To get started writing tests add the following import:

import static org.assertj.android.api.Assertions.assertThat;

Add-On Modules

Modules are also provided for the add-on Android libraries. Add the dependency (listed below) and use the following imports:

  • support-v4: import static org.assertj.android.support.v4.api.Assertions.assertThat;
  • play-services: import static org.assertj.android.playservices.api.Assertions.assertThat;
  • appcompat-v7: import static org.assertj.android.appcompat.v7.api.Assertions.assertThat;
  • mediarouter-v7: import static org.assertj.android.mediarouter.v7.api.Assertions.assertThat;
  • gridlayout-v7: import static org.assertj.android.gridlayout.v7.api.Assertions.assertThat;
  • cardview-v7: import static org.assertj.android.cardview.v7.api.Assertions.assertThat;
  • recyclerview-v7: import static org.assertj.android.recyclerview.v7.api.Assertions.assertThat;
  • palette-v7: import static org.assertj.android.palette.v7.api.Assertions.assertThat;

Extending

The provided assertions have also been designed to be extended for any custom controls you have developed.

public class CustomLayout extends LinearLayout {
  public int getBehavior() {
    /* ... */
  }
}

Use the following pattern to set up your assertions.

public class CustomLayoutAssert extends AbstractLinearLayoutAssert<CustomLayoutAssert, CustomLayout> {
  public static CustomLayoutAssert assertThat(CustomLayout actual) {
    return new CustomLayoutAssert(actual);
  }

  public CustomLayoutAssert(CustomLayout actual) {
    super(actual, CustomLayoutAssert.class);
  }

  public CustomLayoutAssert hasSomeBehavior() {
    isNotNull();
    assertThat(actual.getBehavior())
        .overridingErrorMessage("Expected some behavior but was doing other behavior.")
        .isEqualTo(42)
    return this;
  }
}

Now static import CustomLayoutAssert.assertThat in your test classes.

For more information about writing custom assertions see the official documentation.

Download

Android module:

androidTestCompile 'com.squareup.assertj:assertj-android:1.2.0'

support-v4 module:

androidTestCompile 'com.squareup.assertj:assertj-android-support-v4:1.2.0'

Google Play Services module:

androidTestCompile 'com.squareup.assertj:assertj-android-play-services:1.2.0'

appcompat-v7 module:

androidTestCompile 'com.squareup.assertj:assertj-android-appcompat-v7:1.2.0'

Design library module:

androidTestCompile 'com.squareup.assertj:assertj-android-design:1.2.0'

mediarouter-v7 module:

androidTestCompile 'com.squareup.assertj:assertj-android-mediarouter-v7:1.2.0'

gridlayout-v7 module:

androidTestCompile 'com.squareup.assertj:assertj-android-gridlayout-v7:1.2.0'

cardview-v7 module:

androidTestCompile 'com.squareup.assertj:assertj-android-cardview-v7:1.2.0'

recyclerview-v7 module:

androidTestCompile 'com.squareup.assertj:assertj-android-recyclerview-v7:1.2.0'

palette-v7 module:

androidTestCompile 'com.squareup.assertj:assertj-android-palette-v7:1.2.0'

Snapshots of the development version are available in Sonatype's snapshots repository.

License

Copyright 2013 Square, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Comments
  • Unable to import static method assertThat

    Unable to import static method assertThat

    I replaced the line in my build.gradle file that declared using Fest-Android with one for AssertJ-Android:

    -    androidTestCompile('com.squareup:fest-android:1.0.+') {
    +    androidTestCompile('com.squareup.assertj:assertj-android:1.0.0') {
    

    The issue is that after replacing all static imports of import static org.fest.assertions.api.ANDROID.assertThat; with import static org.assertj.android.api.Assertions.assertThat;, the static import isn't found therefore my Robolectric tests fail to compile. If I change the Gradle line to use compile instead of androidTestCompile, the tests work correctly but obviously that's not optimal nor what the documentation describes.

    The error returned by javac is the following:

    File.java:∞ error: package org.assertj.android.api does not exist
    import static org.assertj.android.api.Assertions.assertThat;
                                         ^
    
    opened by plackemacher 32
  • Android Studio: Each module has to have a unique path

    Android Studio: Each module has to have a unique path

    After pulling the git repository and opening in Android Studio, I get the following error when trying to sync the project with Gradle:

    Error:The modules 'assertj-android', 'assertj-android-root' point to same directory in the file system.
Each module has to have a unique path.

    These modules are in different directories, so I'm pretty confused as to why AS would think they are in the same path.

    opened by sberan 16
  • Resolved versions for app (23.1.1) and test app (22.2.1) differ

    Resolved versions for app (23.1.1) and test app (22.2.1) differ

    Anytime i try to sync my gradle i get this message

    Error:Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.1) and test app (22.2.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
    

    These i believe are the essential excerpts from my gradle file

    testCompile 'junit:junit:4.12'
        testCompile 'org.robolectric:robolectric:3.1-SNAPSHOT'
        testCompile 'org.assertj:assertj-core:3.3.0'
        testCompile 'com.squareup.assertj:assertj-android:1.1.1'
    
    compile 'com.android.support:appcompat-v7:23.1.1'
        compile 'com.android.support:recyclerview-v7:23.1.1'
        compile 'com.android.support:cardview-v7:23.1.1'
        compile 'com.android.support:support-v4:23.1.1'
    
    opened by bubunyo 12
  • Invalid version of support-v4 in POM

    Invalid version of support-v4 in POM

    The POM pushed to Maven central contains this dependency:

    <dependency>
          <groupId>com.android.support</groupId>
          <artifactId>support-v4</artifactId>
          <version>19.1.+</version>
          <scope>compile</scope>
    </dependency>
    

    The version format 19.1.+ is illegal in Maven (i know it comes from Gradle). Please consider modifying the version number.

    opened by WonderCsabo 10
  • Update Android tools & libraries, drop support for Java 7

    Update Android tools & libraries, drop support for Java 7

    This updates the following library and build tool versions:

    • Gradle: 2.9 → 3.2
    • Source repositories: mavenCentral → jcenter
    • Android Plugin for Gradle: 1.5.0 → 2.2.2
    • Android Build Tools: 23.0.2 → 25.0.0
    • Android Support Libraries: 23.1.1 → 25.0.1
    • Android SDK: 23 → 25

    This also drops support for Java 7, which is no longer support by Android Plugin. (See AOSP issue 224738.)

    opened by PiDelport 9
  • Fix hasFlags method in IntentAssert

    Fix hasFlags method in IntentAssert

    Android has same values for flags FLAG_ACTIVITY_MULTIPLE_TASK and FLAG_RECEIVER_NO_ABORT. Hence, any invocation of hasFlags resulted in IllegalStateException being thrown.

    Try, for example:

      @Test
      public void test() {
        assertThat(new Intent().addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT))
            .hasFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
      }
    

    I believe we also need a project with integration tests. Where this test could be written. I personally created one to test your code from master branch. But I do not submit it here: it uses robolectric. Should I submit it? I really do not know whether this change will break something in other place. The project definitely lacks tests IMHO...

    opened by roman-mazur 9
  • Add View tree traversal JQuery inspired assertions

    Add View tree traversal JQuery inspired assertions

    Was just writing a test and really wanted to write something like:

    assertThat(viewGroup).has(textView).withText("fest!");
    

    or perhaps

    assertThat(viewGroup).has(TextView.class).withText("fest!");
    

    is better design.

    opened by christopherperry 9
  • AssertJ module

    AssertJ module

    Have you thought about supporting AssertJ instead of/in addition to fest-assert-2.x? fest-assert-2.x is dormant and if it comes to life again chances are it is going to be less useful (there are plans to remove a lot of assertions, see https://github.com/alexruiz/fest-assert-2.x/issues/159 and https://github.com/joel-costigliola/assertj-core#why-have-we-forked-fest-assert). I'd be willing to provide a patch, but it would be a breaking change (packages have to be renamed) and eventually involve renaming the project to assertj-android.

    opened by aahlenst 8
  • Add Design support library module

    Add Design support library module

    Should address #166

    Is there any guidelines for knowing if I've covered all the APIs / methods that I need to for a given class? I just sorta guessed at ones that people might actually use (IE: Does there need to be a getBackgroundTintList() for FAB?)

    opened by MichaelEvans 7
  • hasText() sometimes returns false negatives

    hasText() sometimes returns false negatives

    Sometimes fails with messages like: "Expected text but was " This happens because the text is actually a CharSequence that doesn't compare nicely with String. In my case it was a SpannableStringBuilder. Maybe a nice way to fix this would be to check whether the 'text' parameter is actually a String and call toString() on actualText before doing the comparison:

    public S hasText(CharSequence text) { isNotNull(); CharSequence actualText = actual.getText(); if (text instanceOf String) actualText = actualText.toString(); assertThat(actualText) // .overridingErrorMessage("Expected text <%s> but was <%s>.", text, actualText) // .isEqualTo(text); return myself; }

    That way in the 1% case where someone really wants to ensure that a text field has some exact configuration of a SpannableStringBuilder as it's text they can still build one up and pass it in, while the rest of the time we'll get the String comparison we'd intuitively expect.

    opened by pgoodwin 7
  • Compilation Error: class file for android.app.TaskStackBuilder not found

    Compilation Error: class file for android.app.TaskStackBuilder not found

    Hey guys,

    First time trying to use this lib. Dropped the dependency in my pom, wrote a quick test just to inflate a View into an Activity, and assert that it isn't null. When I try to compile, I get the error:

    class file for android.app.TaskStackBuilder not found

    I've only tried a single assertion:

    assertThat(view).isNotNull();
    

    the error points back directly to this line.

    opened by christopherperry 7
  • Added assertions for preference-v7 support lib.

    Added assertions for preference-v7 support lib.

    Basically a copy of preference assertions from module assertj-android/,

    • minus some classes/methods not included in preference-v7
    • plus SwitchPreferenceCompat.
    opened by gkylafas 2
  • Warning assertj-android-appcompat-v7 depends on one or more Android Libraries but is a jar

    Warning assertj-android-appcompat-v7 depends on one or more Android Libraries but is a jar

    I keep getting the following warning:

    WARNING: Module 'com.squareup.assertj:assertj-android-design:1.1.1' depends on one or more Android Libraries but is a jar
    WARNING: Module 'com.squareup.assertj:assertj-android-support-v4:1.1.1' depends on one or more Android Libraries but is a jar
    WARNING: Module 'com.squareup.assertj:assertj-android-appcompat-v7:1.1.1' depends on one or more Android Libraries but is a jar
    
    opened by ylogx 6
  • aar/jar stuff isn't working

    aar/jar stuff isn't working

    From #156:

    This seems to have removed

    <packaging>aar</packaging>
    

    from the POM file. As a result we get a Gradle build error

    version com.squareup.assertj:assertj-android-support-v4:1.0.1-SNAPSHOT depends on libraries but is a jar
    
    opened by JakeWharton 0
  • IntenAssert.hasFlags failure with API 21

    IntenAssert.hasFlags failure with API 21

    It looks like with API 21 some of receiver flags have same values as activities flags (FLAG_RECEIVER_NO_ABORT, FLAG_ACTIVITY_MULTIPLE_TASK for example). This actually breaks BitMaskStringBuilder since it expects unique values.

    opened by emartynov 0
Releases(1.1.0)
  • 1.1.0(Aug 15, 2015)

    • New: Design library add-on module! Includes assertions for NavigationView, Snackbar, TabLayout, and TabLayout.Tab.
    • Fix: Correct minSdkVersion declared in Card View, Palette, and Recycler View modules.
    Source code(tar.gz)
    Source code(zip)
Selenium locators for Java/Kotlin that resemble the Testing Library (testing-library.com).

Selenium Testing Library Testing Library selectors available as Selenium locators for Kotlin/Java. Why? When I use Selenium, I don't want to depend on

Luís Soares 5 Dec 15, 2022
A set of TestRules and ActivityScenarios to facilitate UI Testing under given configurations: FontSizes, Locales

AndroidUiTestingUtils A set of TestRules, ActivityScenarios and utils to facilit

Sergio Sastre Flórez 122 Dec 23, 2022
Android UI Testing

User scenario testing for Android Robotium is an Android test automation framework that has full support for native and hybrid applications. Robotium

null 2.8k Dec 14, 2022
Android Unit Testing Framework

Robolectric is the industry-standard unit testing framework for Android. With Robolectric, your tests run in a simulated Android environment inside a

Robolectric 5.6k Jan 3, 2023
Android UI Testing

User scenario testing for Android Robotium is an Android test automation framework that has full support for native and hybrid applications. Robotium

null 2.7k Apr 8, 2021
A sample repo describing best practices for snapshot testing on Android

Road to effective snapshot testing A sample repo describing best practices for snapshot testing on Android. This includes for now: Parameterized Tests

Sergio Sastre Flórez 86 Jan 1, 2023
Testify — Android Screenshot Testing

Testify — Android Screenshot Testing Add screenshots to your Android tests Expand your test coverage by including the View-layer. Testify allows you t

ndtp 43 Dec 24, 2022
A programmer-oriented testing framework for Java.

JUnit 4 JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. For more infor

JUnit 8.4k Jan 9, 2023
A programmer-oriented testing framework for Java.

JUnit 4 JUnit is a simple framework to write repeatable tests. It is an instance of the xUnit architecture for unit testing frameworks. For more infor

JUnit 8.4k Dec 28, 2022
Turbine is a small testing library for kotlinx.coroutines Flow.

A small testing library for kotlinx.coroutines Flow

Cash App 1.8k Jan 5, 2023
Fixtures for Kotlin providing generated values for unit testing

A tool to generate well-defined, but essentially random, input following the idea of constrained non-determinism.

Appmattus Limited 191 Dec 21, 2022
Morsa: Jetpack Compose UI Testing Framework

Morsa: Jetpack Compose UI Testing Framework Test library to ease UI testing with Jetpack Compose Purpose This library aims to add some useful wrappers

HyperDevs 10 Dec 3, 2022
Lovely Systems Database Testing

Lovely DB Testing This repository provides opinionated testing helpers for database testing used at Lovely Systems. License This plugin is made availa

Lovely Systems GmbH 1 Feb 23, 2022
Project for testing intern candidate simple level

RickAndMorty-TestTask Тестовый проект 'Гайд по мультфильму Рик и Морти' для практикантов начального и продвинутого уровня. Структура проекта Структура

null 0 Nov 18, 2021
Very simple Morse API text translator. Mainly to do some testing with jitpack, API development etc.

Very simple Morse text translator API. Far from finish or even being reliable. Use for single sentence. Mainly to test github dependency for Android

Piotr Dymala 0 Dec 30, 2021
Snapshot Testing framework for Kotlin.

KotlinSnapshot Snapshot Testing framework for Kotlin. What is this? Snapshot testing is an assertion strategy based on the comparision of the instance

Pedro Gómez 157 Nov 13, 2022
Android library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests.

Green Coffee Green Coffee is a library that allows you to run your acceptance tests written in Gherkin in your Android instrumentation tests using the

Mauricio Togneri 227 Nov 21, 2022
null 866 Dec 27, 2022
Linkester is an Android library that aims to help Android developers test their deep links implementation.

Linkester Linkester is an Android library that aims to help Android developers test their deep links implementation. The idea is to have a new launche

Ahmad Melegy 79 Dec 9, 2022