startActivity are not working in Android Unit Tests - android

I've tried everything already. The startActivity are not receiving the intent. Here's the code:
public class ColaboradorTeste extends ActivityUnitTestCase<ColaboradorMainActivity> {
private UserDAO userDAO;
private ColaboradorMainActivity activity;
public ColaboradorTeste() {
super(ColaboradorMainActivity.class);
}
#Override
protected void setUp() throws Exception{
super.setUp();
startActivity(new Intent(getInstrumentation().getTargetContext(), ColaboradorMainActivity.class), null, null);
activity = (ColaboradorMainActivity)getActivity().getApplicationContext();
userDAO = new UserDAO(activity);
}
public void testBase() throws Exception{
...
}
}
Here's the error:
java.lang.NullPointerException
at br.fsw.seatafmobile.ColaboradorTeste.setUp(ColaboradorTeste.java:23)
I know the problem is in the startActivity, but I really don't know how to solve it.
If anyone could help I'll really appreciate.

I finally found the solution!
My test is using a database created on the app. So I had to change the Build Variants from Unit Test to Android Instrumentation Tests.

Related

Android, Espresso - Activity stops before whole test is finished when run as part of :app:connectedAndroidTest (runs fine in isolation)

I apologise if this is a bit too vague here, but I'm not allowed to post my whole actual code. All I can say is I have a problem running this test as a part of ./gradlew connectedAndroidTest
#RunWith(AndroidJUnit4.class)
#LargeTest
public class MobileAppSanityTest extends AbstractEspressoTest {
#Rule
public ActivityTestRule<MainActivity> mActivityRule =
new ClearPreferencesActivityTestRule<>(MainActivity.class, getFiles());
#Override
protected Context getContext() {
return mActivityRule.getActivity();
}
#BeforeClass
public static void beforeAll() {
RoboGuice.Util.reset();
}
#Test
public void test_SingleUserFlow() {
navigateSplashScreen();
logIn();
doSomethingElse();
}
}
What happens here is that when I run this test class on its own - it runs fine, but when I run it as a part of 'connectedAndroidTest' the activity is stopped right after 'navigateSplashScreen' and login cannot be performed.
Error I get is:
java.lang.RuntimeException: No activities found. Did you t to launch the activity by calling getActivity() or startActivitySync or similar?
I'm quite new to Espresso and Android in general, so it's a bit hard to wrap my head around this. Please let me know if you need more information. I'll try to provide it out if that's the case.
a jUnit TestCase looks differently; think one can only use Espresso in there.
#RunWith(AndroidJUnit4.class)
public class MainActivityTest extends TestCase {
/** Log Tag */
private static final String LOG_TAG = MainActivityTest.class.getSimpleName();
/** the Activity of the Target application */
private MainActivity mActivity;
#Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<MainActivity>(MainActivity.class) {
};
#Override
public void setUp() throws Exception {
super.setUp();
}
/* obtaining the context from the ActivityTestRule */
#Before
public void setUpTest() {
this.mActivity = this.mActivityRule.getActivity();
}
/* add Espresso code eg. here */
#Test
#UiThreadTest
public void navigateSplashScreen() {
}
#Override
public void tearDown() throws Exception {
super.tearDown();
}
}

How to clean db with ProviderTestCase2 or RenamingDelegatingContext

I do not understand what exactly should I do in order to get a clean and a different db from the one that the app uses.
This is my test class:
public class SQLTest extends ProviderTestCase2{
private static String testDbPrefix = "unitTest_";
public SQLTest (){
super(MyContentProvider.class, MyContract.CONTENT_AUTHORITY);
}
#Override
#Before
public void setUp() throws Exception {
//setContext(InstrumentationRegistry.getTargetContext());
RenamingDelegatingContext context = new RenamingDelegatingContext(InstrumentationRegistry.getTargetContext(), testDbPrefix);
setContext(context);
super.setUp();
}
#Test
public void test1(){
//test logic
}
}
I noticed that it always runs on the db that the app uses, even though I'm using a both ProviderTestCase2 and RenamingDelegatingContext, which are supposed to ensure I'm running with a clean db.
Can anyone explain please what am I missing???
Thanks in advance!

Testing Android Activity with Robolectric, duplicated Otto provider

I have a little problem figuring out how to test my Activity using Robolectric 2.2. I am probably not correctly setting up the lifecycle or the entire test...
In my Activity, I have a Otto producer like this:
#Produce public GetAlarmList produceAlarmList() {
Log.v(this, "Producing GetAlarmList event.");
return new GetAlarmList(mAlarmList);
}
The following is my test.
#RunWith(RobolectricTestRunner.class)
public class GLarmListFragmentTests {
//GLarmMain mActivity;
ActivityController<GLarmMain> mController;
#Before
public void setUp() throws Exception {
mController = Robolectric.buildActivity(GLarmMain.class);
}
#After
public void tearDown() throws Exception {
mController = mController.destroy();
}
#Test
public void shouldHaveListFragment() {
GLarmMain activity = mController.create().start().resume().visible().get();
GLarmListFragment listFragment = (GLarmListFragment) activity.getSupportFragmentManager().findFragmentById(R.id.main_list_frag);
assertNotNull(listFragment);
}
#Test
public void shouldHaveListAdapter() {
GLarmMain activity = mController.create().start().resume().visible().get();
GLarmListFragment listFragment = (GLarmListFragment) activity.getSupportFragmentManager().findFragmentById(R.id.main_list_frag);
FuncAlarmListAdapter listAdapter = (FuncAlarmListAdapter)listFragment.getListAdapter();
assertNotNull(listAdapter);
}
}
Every time I launch it, I receive:
java.lang.IllegalArgumentException: Producer method for type class ar.android.app.glarm.events.GetAlarmList found on type class ar.android.app.glarm.ui.GLarmMain, but already registered by type class ar.android.app.glarm.ui.GLarmMain.
at com.squareup.otto.Bus.register(Bus.java:198)
at ar.android.app.glarm.ui.GLarmMain.onResume(GLarmMain.java:461)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1184)
at android.app.Activity.performResume(Activity.java:5082)
at org.fest.reflect.method.Invoker.invoke(Invoker.java:112)
at org.robolectric.util.ActivityController$6.run(ActivityController.java:216)
at org.robolectric.shadows.ShadowLooper.runPaused(ShadowLooper.java:256)
at org.robolectric.util.ActivityController.invokeWhilePaused(ActivityController.java:214)
at org.robolectric.util.ActivityController.resume(ActivityController.java:152)
at ar.android.app.glarm.test.GLarmListFragmentTests.shouldHaveListAdapter(GLarmListFragmentTests.java:51)
Does someone have the same issue? How can I solve it?
Found the problem, leaving it here for reference.
I was not handling the pause()/onPause() life-cycle step and therefore never calling:
#Override
protected void onPause() {
super.onPause();
Log.v(this, ".onPause()");
mBus.unregister(this); // unregisters.
}
Changing the above code as following solved:
#After
public void tearDown() throws Exception {
mController = mController.pause().stop().destroy();
}

Android ProviderTestCase2: Fails in Run mode, Passes in Debug mode

I'm testing database using ProviderTestCase2 super class. Here is my code snippet:
public class MyProviderTest extends ProviderTestCase2<MyProvider>{
private static MockContentResolver resolver;
private static IsolatedContext context;
public MetaDataProviderTest() {
super(MyProvider.class, Provider.AUTHORITY);
}
#Override
protected void setUp() throws Exception {
try{
super.setUp();
resolver = getMockContentResolver();
} catch(Exception e){
}
}
}
public void testfirst(){
Cursor cursor = resolver.query(ProviderContract.Channels.CHANNEL_URI,null,null,null,null);
....
}
}
When I debug the above code Im getting the passed result. When I run it, I get Null cursor implying there is no such table as channel. Please help in solving this. Where did I go wrong?
There was race condition. Introduced delay in Setup(). It's working fine. But I don't know whether this is the exact solution.
you should write the code :
MockContentResolver.addProvider(authority, yourprovider);
then have a try

Android JUNIT testing stuck

I'm new at JUnit tests, I'm trying to test database access through this code:
public class SeuticketTest extends ActivityInstrumentationTestCase2<Seuticket> {
private Seuticket mActivity;
public SeuticketTest(String name) {
super("br.com.code.seuticket.android.view",Seuticket.class);
setName(name);
}
#Override
protected void setUp() throws Exception {
super.setUp();
mActivity = this.getActivity();
}
public void testTicketInsertion() {
Ticket ticket = new Ticket("123453", "Vip", new Date(), "Vila Country");
PersistenceTicket persistence = new PersistenceTicket(mActivity);
persistence.addTicket(ticket);
assertEquals(persistence.fetchTicket(ticket.getTicketCode()).getTicketCode(),ticket.getTicketCode());
}
public void testUserInsertion() {
User user = new User();
user.setPin("1234");
user.setPhone("9241173");
PersistenceUser persistence = new PersistenceUser(mActivity);
persistence.addUser(user);
assertEquals(persistence.fetchUser().getPin(), user.getPin());
}
}
But my tests get stuck after complete the testTicketInsertion, the second test keep running forever, and sometimes before it run the tests this message shows at the console:
Test run failed: Process crashed.
Any ideas?
Hope to find an answer here.
Thanks people!
I am brand new to JUnit testing in Android and ran into the same problem. Make sure you have the tearDown method overridden and are making the call to super.
protected void tearDown() throws Exception {
super.tearDown();
}

Categories

Resources