AndroidUnitTest


Source link: https://github.com/florent37/AndroidUnitTest

Android Unit Test

Save time & clear your unit tests on Android !

Use annotations to inject Context, Activities, Fragments and Views into your tests

Usage

@RunWith(CustomTestRunner.class) public class MainActivityTest {

  @Rule public AndroidUnitTest androidUnitTest = AndroidUnitTest.rule();

@RContect Context context; //inject the app context
  @RActivity MainActivity activity; //generates the tested activity
  @Mock User user; //mock an user

@Test
  public void testDisplayUser() throws Exception {

// Given

given(user.getName()).willReturn("florent");

// When

activity.display(user);

// Then

assertThat(activity.textView.getText()).isEqualTo("florent");

  
}
 
}

TestRunner

Simplify Robolectric Integration

public class CustomTestRunner extends AndroidUnitTestRunner {

  public CustomTestRunner(Class<?> testClass) throws InitializationError {

super(testClass, BuildConfig.FLAVOR, BuildConfig.BUILD_TYPE, BuildConfig.APPLICATION_ID, TestMyApplication.class);

  
}
 
}

Activity

Set initial activity state (by default activity is created())

@RunWith(CustomTestRunner.class) public class MyTest {

  @Rule public AndroidUnitTest androidUnitTest = AndroidUnitTest.rule();

@RActivity(state = CREATED / STARTED / RESUMED / PAUSED / STOPPED / DESTROYED)
  MainActivity activity;

 @Test
  public void testMyFunction(){

 androidUnitTest.activity().resume();

  
}
  
}

Note that the injected activity is a spy !

verify(activity, times(2)).someMethod(anyInt());

Context

Retrieve Context easily

@RunWith(CustomTestRunner.class) public class MyTest {

  @Rule public AndroidUnitTest androidUnitTest = AndroidUnitTest.rule();

@RContext Context context; 
}

Note that the injected context is a spy !

verify(context, times(2)).someMethod(anyInt());

View

@RunWith(CustomTestRunner.class) public class MyTest {

  @Rule public AndroidUnitTest androidUnitTest = AndroidUnitTest.rule();

@RView CustomView customView;

 @Test
  public void testDisplayUser() throws Exception {

// Given

given(user.getName()).willReturn("florent");

// When

mainView.display(user);

// Then

verify(customView).displayText("florent");

  
}
 
}

Note that the injected view is a spy !

Fragment

@RunWith(CustomTestRunner.class) public class MyTest {

  @Rule public AndroidUnitTest androidUnitTest = AndroidUnitTest.rule();

@RFragment MyFragment myFragment;
  @Mock User user;

 @Test
  public void testDisplayUser() throws Exception {

// Given

given(user.getName()).willReturn("florent");

// When

myFragment.display(user);

// Then

verify(myFragment).displayText("florent");

  
}
 
}
@RunWith(CustomTestRunner.class) public class MyTest {

  @Rule public AndroidUnitTest androidUnitTest = AndroidUnitTest.rule();

@RFragment(

attached = true / false,

tag = "fragmentTag"
  )
  MyFragment myFragment;

  @Test
  public void testMyFunction() throws Exception {

androidUnitTest.fragment().addToActivity(myFragment)
  
}
 
}

Note that the injected fragment is a spy !

Download

testCompile 'com.github.florent37:androidunittest:(last version)'  testCompile 'junit:junit:4.12' testCompile 'org.mockito:mockito-core:1.10.19' testCompile 'org.robolectric:robolectric:3.0'

Credits

Author: Florent Champigny http://www.florentchampigny.com/

License

Copyright 2016 florent37, 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. 

Resources

Pop

A library to build android dialog quick and easy.

Run GET, POST and DOWNLOAD API on Android. Library takes care of Cookie Management and http caching.

IRecyclerView is a custom RecyclerView that supports pull-to-refresh, pull-to-loadmore, customize refresh header and loadmore footer, add header views and footer views.

Android library for managing multiple stacks of fragments.

An Android library that enhances the StrictMode reporting.

  • Head-up Notification of StrictMode violations.
  • Custom Actions that called when StrictMode violations is happend.
  • Violation History Viewer that automatically installed.

Grenade is annotation based intent builder for activities and services. By using this library, you can build Intent with extras and retrieve extras by type safe way and less code.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes