Jonathan Schneider
Jonathan Schneider

Reputation: 27727

Keep an instrumented Activity alive after test case

Suppose you are constructing a test case for the Android platform using a class with a signature like:

public class AccountTest extends ActivityInstrumentationTestCase2<MainActivity> { ... }

Say we have a test method like this using the Robotium framework:

public void testCreateAccount() {
    solo.clickOnButton("Add Account");
    solo.clickOnButton("Next");

    ...
}

When the test case completes, the instrumented activity is swiftly killed. Is there any way to keep it alive upon termination, at least for the purpose of determining what you want to do next and coding the next few lines?

Upvotes: 3

Views: 2098

Answers (3)

Huiyu
Huiyu

Reputation: 77

I have the same problem.Finally i use Sleep().

while(true)
{
   Thread.Sleep(1000);
   // do other things when the main thread wake
}

you can put the above code in arbitrary test method,then the instrument Activity will not end.

Hope it helps you.

Upvotes: 0

Jonathan Schneider
Jonathan Schneider

Reputation: 27727

As it turns out, it is easy to accomplish essentially what I want by using the Nativedriver library:

http://code.google.com/p/nativedriver/

Omitting driver.quit() at the end of the test case keeps the activity alive, which is very handy when developing the test case initially.

Upvotes: 1

yorkw
yorkw

Reputation: 41126

Android JUnit Test is built on top of JUnit, as a consequence, it obeys the basic rules of JUnit test life cycle:

  • Calls the test case's setUp( ) method
  • Calls the test method
  • Calls the test case's tearDown( ) method

When the test case completes, the instrumented activity is swiftly killed.

See the source code of ActivityInstrumentationTestCase2 for the reason:

@Override
protected void tearDown() throws Exception {
  // Finish the Activity off (unless was never launched anyway)
  Activity a = super.getActivity();
  if (a != null) {
    a.finish();
    setActivity(null);
  }

  // Scrub out members - protects against memory leaks in the case where someone 
  // creates a non-static inner class (thus referencing the test case) and gives it to
  // someone else to hold onto
  scrubClass(ActivityInstrumentationTestCase2.class);

  super.tearDown();
}

Is there any way to keep it alive upon termination, at least for the purpose of determining what you want to do next and coding the next few lines?

Possible workarounds are:

  1. Completely override teardown() method in your AccountTest class (which extends ActivityInstrumentationTestCase2 class), without calling super.tearDown();
  2. Create customized ActivityInstrumentationTestCase3 class (wich extends ActivityTestCase class) to avoid finish activity in teardown() method.

In either approach, you should implement your teardown() method carefully to avoid memory leaks.

Hope this helps.

Upvotes: 2

Related Questions