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 starting an application, usually on an emulator or on a device. However, when I test Activity using 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?

+6
source share
1 answer

This is part of the design. Have you tried using ActivityInstrumentationTestCase2 instead? There is no guarantee that it will work, but there will be more chances. The context available to you in ActivityInstrumentationTestCase2 supports more functions.

Real unit testing in Android is tricky. Especially for events, you must allow yourself to β€œcheat” and perform functional testing.

+2
source

All Articles