Nathan
Nathan

Reputation: 1478

ActivityUnitTestCase getActionBar() returns null

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?

Upvotes: 6

Views: 837

Answers (1)

Joe Malin
Joe Malin

Reputation: 8641

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.

Upvotes: 2

Related Questions