I am trying to mock dependencies like what is suggested in https://artemzin.com/blog/how-to-mock-dependencies-in-unit-integration-and-functional-tests-dagger-robolectric-instrumentation/
Unfortunately I can't get past the following error when I run my AndroidJunit4 test :
Test running failed: Unable to find instrumentation info for: ComponentInfo{com.fisincorporated.aviationweather.test/android.support.test.runner.AndroidJUnitRunner}
I tried various SO solutions that were not Android Studio version dependent with no luck
My app level gradle code snippet is:
android {
...
defaultConfig {
...
testInstrumentationRunner "com.fisincorporated.aviationweather.app.OverrideApplicationTestRunner"
}
...
}
My OverrideApplicationTestRunner is:
public class OverrideApplicationTestRunner extends AndroidJUnitRunner {
#Override
#NonNull
public Application newApplication(#NonNull ClassLoader cl,
#NonNull String className,
#NonNull Context context)
throws InstantiationException,
IllegalAccessException,
ClassNotFoundException {
return Instrumentation.newApplication(WeatherApplicationTest.class, context);
}
}
WeatherApplicationTest
public class WeatherApplicationTest extends WeatherApplication {
#Override
protected void createDaggerInjections() {
component = DaggerDiComponent.builder()
.appModule(new AppModule(this) {
#Override
public String providesAppSharedPreferencesName() {
return "SHARED_AIRPORT_FUNCTIONAL_TEST";
}
public Retrofit provideAppRetrofit() {
return new AppRetrofit(new MockInterceptor()).getRetrofit();
}
})
.build();
component.inject(this);
}
}
And AirportWeatherActivityTest
#RunWith(AndroidJUnit4.class)
public class AirportWeatherActivityTest {
#Rule
public ActivityTestRule<AirportWeatherActivity> mActivityRule =
new ActivityTestRule<>(AirportWeatherActivity.class, true, false);
#Test
public void someTest() {
Context targetContext = InstrumentationRegistry.getTargetContext();
Intent intent = new Intent(targetContext, AirportWeatherActivity.class);
mActivityRule.launchActivity(intent);
assertThat(mActivityRule.getActivity().airportWeatherViewModel.airportWeatherList.size(),is(0));
}
}
androidTest directory structure is below:
I have found that if I run the following test, it works, i.e. I see that WeatherApplicationTest is being executed. So it would seem that testInstrumentationRunner is finding my OverrideApplicationTestRunner.
#RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
#Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.fisincorporated.aviationweather", appContext.getPackageName());
}
}
So is problem caused by using an ActivityTestRule?
P.S. I neglected to say I am a newbie on testing so my apologizes if I am missing something obvious.
Switching android plugin version to 2.2.3 and then back to 2.3.0 back, cleaning project and building fixes the issue.
Related
#Before class does not start the activity. For this reason, no views to do actions on are available. Is it possible to have the activity started before #BeforeClass
An exemplary test that fails due to this:
#RunWith(AndroidJUnit4.class)
public class MakeFeedingTest {
#Rule
public ActivityScenarioRule<MainActivity> scenarioRule = new ActivityScenarioRule<>(MainActivity.class);
#BeforeClass
public static void setup() {
onView(withId(R.id.add)).perform(click());
onView(withId(R.id.save)).perform(click());
}
#Test
public void superBasicTest() {
onView(withId(R.id.new_element)).check(matches(isDisplayed()));
}
}
How can I make the activity start before #BeforeClass is executed, so that the test does not fail anymore?
Usecase: Add an element to a list before the other tests are exectued.
That is not relevant design pattern here, and I wouldnt do it in that way.
For this to work, do something like this:
#RunWith(AndroidJUnit4.class)
public class MakeFeedingTest {
#Rule
public ActivityScenarioRule<MainActivity> scenarioRule = new ActivityScenarioRule<>(MainActivity.class);
#BeforeClass
public static void setup() {
}
#Test
public void superBasicTest() {
clickButtons()
onView(withId(R.id.new_element)).check(matches(isDisplayed()));
}
private void clickButtons() {
onView(withId(R.id.add)).perform(click());
onView(withId(R.id.save)).perform(click());
}
}
If you're insisting on using it in this way, add aditional parameters to the screnario rule as following and see if that will work:
#Rule
public ActivityScenarioRule<MainActivity> scenarioRule = ActivityTestRule(MainActivity.class.java, true, true)
I'm trying to setup and instrumental unit test for Activity with FirebaseAuth. When I run the application, everything works just fine. The problem is within the setup of instrumental unit tests.
Activity:
public final class GoogleSignInActivity extends AppCompatActivity{
#Override
protected void onCreate(final Bundle savedInstanceState) {
...
if (FirebaseApp.getApps(this).isEmpty()) {
FirebaseApp.initializeApp(this);
}
mFirebaseAuth = FirebaseAuth.getInstance();
}
}
Test:
#RunWith(AndroidJUnit4.class)
public class GoogleSignInActivityIntegrationTest extends UiTestPrerequesites {
#Rule
public final ActivityTestRule<GoogleSignInActivity> mActivityRule = new ActivityTestRule<>(
GoogleSignInActivity.class, false, true);
#Before
public void setup(){
if (FirebaseApp.getApps(InstrumentationRegistry.getContext()).isEmpty()) {
FirebaseApp.initializeApp(InstrumentationRegistry.getContext());
}
}
#Test
#SmallTest
public void implements_GoogleSignInWorkerFragment_GoogleSignInUiChangesListener() {
//FirebaseApp.initializeApp(InstrumentationRegistry.getContext()); (this doesn't help)
assertThat(mActivityRule .getActivity(),
notNullValue());
}
}
Exception (only when running test, not app):
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.twofortyfouram.ui.test. Make sure to call FirebaseApp.initializeApp(Context) first.
I think your issue with applicationID ( a.k.a package name ). you should add your application Id for testing to Firebase project account as well.
it has suffix: test
In general it looks like:
[ApplicationID].test
i.e.
com.apipas.android.hello.test
release applicationId is
com.apipas.android.hello
I hope that may help you,'.
Getting an ResourceNotFoundException when using a library with Robolectic 3.0-rc3. The resource is declared in build.gradle with compile 'net.danlew:android.joda:2.8.0'. Specifically this is the Android port of Joda-Time.
android.content.res.Resources$NotFoundException: Unable to find resource ID #0x7f0501da
at org.robolectric.shadows.ShadowResources.checkResName(ShadowResources.java:343)
at org.robolectric.shadows.ShadowResources.getResName(ShadowResources.java:333)
at org.robolectric.shadows.ShadowResources.openRawResource(ShadowResources.java:382)
at android.content.res.Resources.openRawResource(Resources.java)
at net.danlew.android.joda.ResourceZoneInfoProvider.openResource(ResourceZoneInfoProvider.java:120)
at net.danlew.android.joda.ResourceZoneInfoProvider.<init>(ResourceZoneInfoProvider.java:39)
Application class:
#Override
public void onCreate() {
super.onCreate();
JodaTime.init(this);
}
My test class:
#RunWith(RobolectricGradleTestRunner.class)
#Config(constants = BuildConfig.class,
sdk = 21)
public class MyTest {
#Before
public void setup() {
}
#Test
public void myTest() {
//Test my stuff
}
}
You need to initialise the library in your tests, with the Robolectric runtime environment. So add this to your setup() methods.
JodaTimeAndroid.init(RuntimeEnvironment.application);
So your test would look something like this:
#RunWith(RobolectricGradleTestRunner.class)
#Config(constants = BuildConfig.class, sdk = 21)
public class MyApplicationTest {
#Before
public void setup() {
JodaTimeAndroid.init(RuntimeEnvironment.application);
}
#Test
public void myTest() {
//Test my stuff
DateTime aDateTime = new DateTime();
DateTime bDateTime = new DateTime(aDateTime);
assertEquals(aDateTime, bDateTime);
}
}
I want to use Dagger injections in my robolectric tests but I have trouble with set it up. Where is error in my code sample. How can I make this work?
My main module
#Module(
includes = DatabaseModule.class,
injects = {
MainActivity.class,
}
)
public class MainModule {
private final MyApplication application;
public MainModule(MyApplication application) {
this.application = application;
}
My test module
#Module(
overrides = true,
includes = MainModule.class,
injects = {
TestMyApplication.class,
MyApplication.class
}
)
public class TestModule {
}
My production main class
public class MyApplication extends Application {
#Inject
public MyApplication() {
super();
}
#Override
public void onCreate() {
super.onCreate();
graph = ObjectGraph.create(getModules().toArray());
inject(this);
}
...
}
My robolectric test application class
public class TestMyApplication extends MyApplication {
#Override
protected List<Object> getModules() {
List<Object> modules = super.getModules();
return modules;
}
public void injectMocks(Object object) {
((TestMyApplication) Robolectric.application).inject(object);
}
Error:
java.lang.RuntimeException: java.lang.IllegalArgumentException: No inject registered for members/info.korzeniowski.MyApplication.TestMyApplication. You must explicitly add it to the 'injects' option in one of your modules.
When I change in My robolectric application class method to this:
#Override
protected List<Object> getModules() {
List<Object> modules = super.getModules();
modules.add(new TestModule());
return modules;
}
Result:
java.lang.RuntimeException: java.lang.IllegalStateException: Module adapter for class info.korzeniowski.walletplus.test.TestModule could not be loaded. Please ensure that code generation was run for this module.
Update
gradle.build:
compile 'com.jakewharton:butterknife:5.1.2'
def daggerVersion = '1.2.+'
apt "com.squareup.dagger:dagger-compiler:$daggerVersion"
compile "com.squareup.dagger:dagger:$daggerVersion"
compile "com.squareup:javawriter:2.2.1"
You should provide the TestModule and you are doing it right (TestModule must be in the list of modules returned from getModules). You can find solution for the second error here: Dagger example built through eclipse fails with 'Please ensure that code generation was run for this module.'
I’m trying to test an Activity with Mockito & Dagger. I have been able to inject dependencies to Activity in my application but when testing the Activity, I have not been able to inject mock to the Activity. Should I inject Activity to test or let getActivity() create it?
public class MainActivityTest extends
ActivityInstrumentationTestCase2<MainActivity> {
#Inject Engine engineMock;
private MainActivity mActivity;
private Button mLogoutBtn;
public MainActivityTest() {
super(MainActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
// Inject engineMock to test
ObjectGraph.create(new TestModule()).inject(this);
}
#Override
protected void tearDown() {
if (mActivity != null)
mActivity.finish();
}
#Module(
includes = MainModule.class,
entryPoints = MainActivityTest.class,
overrides = true
)
static class TestModule {
#Provides
#Singleton
Engine provideEngine() {
return mock(Engine.class);
}
}
#UiThreadTest
public void testLogoutButton() {
when(engineMock.isLoggedIn()).thenReturn(true);
mActivity = getActivity();
mLogoutBtn = (Button) mActivity.findViewById(R.id.logoutButton);
// how to inject engineMock to Activity under test?
ObjectGraph.create(new TestModule()).inject(this.mActivity);
assertTrue(mLogoutBtn.isEnabled() == true);
}
}
I use Mockito and Dagger for functional testing.
The key concept is that your test class inherits from ActivityUnitTestCase, instead of ActivityInstrumentationTestCase2; the latter super-class call onStart() life-cycle method of Activity blocking you for inject your test doubles dependencies, but with first super-class you can handle the life-cycle more fine-grained.
You can see my working examples using dagger-1.0.0 and mockito for test Activities and Fragments in:
https://github.com/IIIRepublica/android-civicrm-test
The project under test is in:
https://github.com/IIIRepublica/android-civicrm
Hope this helps you
I did some more experimenting and found out that Dagger is not able to create activity correctly when it is injected to test. In the new version of test, testDoSomethingCalledOnEngine passes but onCreate is not called on the MainActivity. The second test, testDoSomethingUI fails and there are actually two instances of MainActivity, onCreate gets called to the other instance (created by ActivityInstrumentationTestCase2 I quess) but not to the other. Maybe the developers at Square only thought about testing Activites with Robolectric instead of Android instrumentation test?
public class MainActivityTest extends
ActivityInstrumentationTestCase2<MainActivity> {
#Inject Engine engineMock;
#Inject MainActivity mActivity;
public MainActivityTest() {
super(MainActivity.class);
}
#Override
protected void setUp() throws Exception {
super.setUp();
// Inject engineMock to test & Activity under test
ObjectGraph.create(new TestModule()).inject(this);
}
#Module(
includes = MainModule.class,
entryPoints = MainActivityTest.class,
overrides = true
)
static class TestModule {
#Provides
#Singleton
Engine provideEngine() {
return mock(Engine.class);
}
}
public void testDoSomethingCalledOnEngine() {
when(engineMock.isLoggedIn()).thenReturn(true);
mActivity.onSomethingHappened();
verify(engineMock).doSomething();
}
#UiThreadTest
public void testDoSomethingUI() {
when(engineMock.isLoggedIn()).thenReturn(true);
mActivity.onSomethingHappened();
Button btn = (Button) mActivity.findViewById(R.id.logoutButton);
String btnText = btn.getText().toString();
assertTrue(btnText.equals("Log out"));
}
}
I have put everything together and made demo app that shows how to test with dagger: https://github.com/vovkab/dagger-unit-test
Here is my pervious answer with more details:
https://stackoverflow.com/a/24393265/369348