开发者

How to test a method which start new activity?

I have a problem with writing a test case for my app.

At first maybe I'll tell how the app works. The first screen is the login screen , after successful login, a new activity is shown and the user credentials are saved to SharedPreferences so that when the activity starts again and user hadn't log out, the app starts on the second activity screen.

I want to test the first activity with the login. My main problem is how to test successful login. If the login and password are valid, an intent to the new activity is created and the new activity is started. My code for this method is shown below:

public void testLoginValid() throws Throwable {
    for(index = 0; index < validEmails.length; index++) {
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                emailEditView.setText(validEmails[index]);
                passwordEditView.setText(defaultPassword);开发者_JS百科
                logIn.performClick();
            }
        });
        getInstrumentation().waitForIdleSync();
        //how to check if the activity started and how to go back?
    }
}

Is this a good way to test such case? The problem is when the login is valid and it logs in, the rest of the test cases hang because the active activity has changed and I don't know how to simulate it's finish are something like this. How to do this? Or maybe I should write method for each of the logins (but I don't think it is a good practice...). Thanks in advance for any help.


If your task is to test logging in, you may replace the actual new activity start by some mock action and check if this action starts. Hope this helps.


The problem with making temporary changes to your code in order to run tests is that you're not testing the "real" code and you can only run tests occasionally. Much better is to set things up so that you can run all of your tests, automatically, whenever you want to. This is the idea behind Test Driven Development.

Unfortunately, Android makes this much more difficult than it should be - but things are improving:

For off-device testing, look at Robolectric.

For on-device testing, look at Borachio.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜