My FragmentActivity
calls getActionBar()
in onCreate()
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_expense);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
This works fine when running the app normally on the emulator or on a device. However, when I test the Activity with a ActivityUnitTestCase
, getActionBar()
always returns null.
public class NewTransactionTest extends ActivityUnitTestCase<TransactionEditActivity> {
private RenamingDelegatingContext myContext;
private DatabaseHelper myHelper;
private RuntimeExceptionDao<Account,Long> myDao;
private Account myBankAccount1;
private Account myBankAccount2;
private Account myCategory1;
private Account myCategory2;
private Budget myBudget;
public NewTransactionTest() {
super(TransactionEditActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
myContext = new RenamingDelegatingContext(getInstrumentation().getTargetContext(), "test");
myContext.deleteDatabase(DatabaseHelper.DATABASE_NAME);
}
@UiThreadTest
public void testPreConditions() throws Throwable {
setActivityContext(myContext);
final TransactionEditActivity activity = startActivity(new Intent(), null, null);
}
Does anyone know why getActionBar()
returns null for unit tests?
It's part of the design. Have you tried using ActivityInstrumentationTestCase2 instead? No guarantee that it will work, but there's a better chance. The Context that's available to you in ActivityInstrumentationTestCase2 supports more features.
Real unit testing in Android is hard to do. Especially for Activities, you should allow yourself to "cheat" and do functional testing instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With