Android unit testing and interfaces -


i have been having quite bit of trouble implementing unit testing on android. simple test, i've been trying match string retrieved string resources:

string mystring = myactivity.getresources().getstring(r.string.teststring)); 

however, when unit testing invariably results in null pointer exception. includes robolectric junit implementation delivered android sdk.

one possible solution approach retrieval of resources in manner similar data access object. is, create interface through string resources accessed. allow me mock access string resource. similarly, separate non-android dependent behavior of, say, activity, separate pojo class. allow me run unit tests using standard java testing tools. in fact, potentially delegate android infrastructure related activity interface.

this seems lot of jumping through hoops unit testing. worth it? there more viable approach?

it turned out, problem activity has gotten in actual test method. so, example, method looks this:

public void testgetactivityresourcestring() {      activity myactivity = this.getactivity();     string mystring = myactivity.getresources().getstring(r.string.hello);     assert.assertnotnull(mystring); } 

whereas before creating activity in setup. giveaway in docs:

"for each test method invocation, activity not created until first time method called."

this real hassle figure out. example helloworldtest doesn't work same reason.

here's full entry:

public t getactivity () since: api level 3 activity under test, starting if necessary.

for each test method invocation, activity not created until first time method called.

if wish provide custom setup values activity, may call setactivityintent(intent) and/or setactivityinitialtouchmode(boolean) before first call getactivity(). calling them after activity has started have no effect.

note: activities under test may not started within ui thread. if test method annotated uithreadtest, activity started automatically before test method run. still call method in order activity under test.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -