Instrumental unit testing of activity with FirebaseAuth - android

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,'.

Related

Android HiltTest: The component was not created. Check that you have added the HiltAndroidRule

I have a util method which will go some actiivty by routing.
// RoutingUtil.java
public static void goRouting(Context context, String routing);
And I want test this method.
So I did something like this
#RunWith(AndroidJUnit4.class)
#HiltAndroidTest
public class RoutingUiUtilsTest {
#Rule
public HiltAndroidRule hiltRule = new HiltAndroidRule(this);
#Before
public void setUp() {
hiltRule.inject();
}
#Test
public void testSmartGo() {
ActivityScenario.launch(MainActivity.class);
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
RoutingUtil.goRouting(context, "", "schema://a_activity_path");
}
}
The dest Activity is AActivity which used the hilt by annoutation #AndroidEntryPoint
#AndroidEntryPoint
class AActivity extends Activity {
}
Then I run test in terminal
./gradlew connectedAndroidTest
And error throws
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.somepackage/com.somepackage.AActivity}:
java.lang.IllegalStateException: The component was not created. Check
that you have added the HiltAndroidRule
I think the reason is I didn't start AActivity by hilt test componet, like ActivityScenario.launch(AActivity.class);, but what I want test is RoutingUtil.goRouting so I can't use hilt test component.
So how to test RoutingUtil.goRouting?

Espresso start activity before #BeforeClass

#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)

Firebase Analytics initialise for unit test (Mockito) in Android

I am running a unit test with
#RunWith(MockitoJUnitRunner.class)
I have used firebase Analytics to log events
MyApplication.getAnalytics().getInstance(appContext).logEvent(eventType, bundle)
and this in my Application class
public static FirebaseAnalytics getAnalytics() {
return FirebaseAnalytics.getInstance(appContext);
}
Now while running tests, I am getting NullPointerException. What will be the right way to initialize Analytics for my unit tests or just ignore them.
I am not getting the context in case I try to initialize it in my setup method of tests.
You can create a mock application class that extends your application class and then overrides getAnalytics with a stubbed value or mock object. Also you should make your getAnalytics method non-static as it's easier for testing and you can pass the reference via dependency injection or you can use a static reference to the application class (but that isn't very testable so I would choose the first option)
public class MockApplication extends MyApplication {
public FirebaseAnalytics getAnalytics() {
return mock(FirebaseAnalytics.class)
}
}
Then you can use the #Config annotation to configure your test runner like this
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.M, application = MockApplication.class)
Check this link out https://github.com/robolectric/robolectric/wiki/Using-PowerMock
Refactor yours like this:
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class)
#PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" })
#PrepareForTest(FirebaseAnalytics.class)
public class TestClass {
#Rule
public PowerMockRule rule = new PowerMockRule();
private FirebaseAnalytics firebase;
#Test
public void testMocking() {
firebase = PowerMockito.mock(FirebaseAnalytics.class);
Context context = PowerMockito.mock(Context.class);
PowerMockito.mockStatic(FirebaseAnalytics.class);
Mockito.when(FirebaseAnalytics.getInstance(context)).thenReturn(firebase);
}
}

Mocking dependency error with AndroidJunitRunner and Dagger2

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.

Android functional testing with Dagger

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

Categories

Resources