Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 359
Nathan Avatar asked Nov 04 '12 12:11

Nathan


1 Answers

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.

like image 189
Joe Malin Avatar answered Nov 14 '22 07:11

Joe Malin