Unit testing login method

Viewed 1995

I am developing an Android application where testing is part of development process. Testing in general is new domain for me therefore, i struggle often. I need an advice on unit testing a method which I use to perform a user login. Since method is void and implements callbacks I assume that either class or some of the objects should be mocked. In my application I use JUnit, Robolectric and Mockito for testing purposes.

I was able to perform a test to check if method with its parameters is being called but I am curious(dont know) how can I test the onResponse & onErrorResponse callbacks. I have provided the code below. Thanks in advance.

 public void loginUser(String email,String pass){
        try {
            requestQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
            StringRequest request = new StringRequest(Request.Method.POST, Url+"/checkUser.php", new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    if(response.contains("present")){
                        Toast.makeText(getActivity(), "Welcome", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getActivity(), MainActivity.class);
                        startActivity(intent);
                    }
                    else{
                        Toast.makeText(getActivity(), response, Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
                }
            }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String,String> parameters = new HashMap<String,String>();
                    parameters.put("email",email);
                    parameters.put("password",pass);

                    return parameters;
                }
            };
            requestQueue.add(request);
        }catch (Exception o){Log.w("TAG",o.getMessage());}
    }//loginUser

@Test
public void testLoginCall() throws Exception {
    loginFragment = Mockito.mock(LoginFragment.class);
    doNothing().when(loginFragment).loginUser("email","pass");
    loginFragment.loginUser("email","pass");
    verify(loginFragment,times(1)).loginUser("email","pass");
}
0 Answers
Related