mockito when在junit中返回null

时间:2017-12-08 11:32:54

标签: junit mockito

我一直在使用mockito编写测试用例。以下是测试用例中的代码。

@RunWith(SpringRunner.class)
public class LoginControllerTest {

    private MockMvc mockMvc;

    @InjectMocks    
    private LoginService loginService;

    @Mock
    private LoginController loginController;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in standalone mode
        mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();

    }

    @Test
    public final void test() throws Exception {

        // Assign
        when(loginService.test()).thenReturn("hello");

        // act
        mockMvc.perform(get("/hello"))
                // Assertion
                .andExpect(status().isOk())
                .andExpect(content().string("Message from service: hello"));
        verify(loginService).test();
    }

    @Test
    public final void usernameInvalidAndPassword() throws Exception {

        User userData = new User();
        userData.setUserName("akhila.s@cloudium.io");
        userData.setPassword("Passw0rd");


        User userDataNew = new User();
        userDataNew.setUserName("akhila.s@cloudium.io");
        userDataNew.setPassword("Passw0rd");


        JSONObject requestBody = new JSONObject();

        requestBody.put("userName", "akhila.s@cloudium.io");
        requestBody.put("password", "Passw0rd");

        JSONObject responseBody = new JSONObject();

        responseBody.put("status_code", "200");
        responseBody.put("message", "ok");

        // Assign
        when(loginService.saveUser(userData)).thenReturn(userDataNew);

        // act
        mockMvc.perform(get("/login")
                .param("userName", "akhila.s@cloudium.io")
                .param("password", "Passw0rd"))
                // Assertion
                .andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
    }

对于第一个测试用例,它的工作正常,但对于第二个测试,它总是返回null。有人可以帮忙吗?提前致谢

2 个答案:

答案 0 :(得分:1)

您的LoginController和LoginService上的注释错误。您正在测试控制器,因此您不想模拟它,并且您正在对您的服务进行存根方法,因此这需要模拟:

      Cursor infoCursor= infodb.rawQuery("SELECT photo FROM phone", null);
        ImageView moviePoster = (ImageView) findViewById(R.id.productPhoto);
        infoCursor.moveToFirst();
        if (!infoCursor.isAfterLast()) {
            if (infoCursor.getInt(infoCursor.getColumnIndex(String.valueOf(ProductSQLiteHelper.PRODUCT_HOT))) == 1) {
                res = this.getResources();
                String posterResourceName = infoCursor.getString(infoCursor.getColumnIndex(ProductSQLiteHelper.PRODUCT_PHOTO));
                Log.v("resource name",posterResourceName);
                int resId = res.getIdentifier(posterResourceName, "drawable", getPackageName());
                moviePoster.setImageResource(resId);
            }
        }

答案 1 :(得分:0)

在我看来,你必须要么:

1)引入基于usernamepassword的equals方法,因为在测试方法中创建的User对象与您创建和使用的对象不同测试。

2)在您的设置中使用通配符:

when(loginService.saveUser(Mockito.any(User.class))).thenReturn(userDataNew);