public User login(String userName, String password) { for (User user : LoginService.existingUsers) { if (user.getUserName().equals(userName) && DigestUtils.md5Hex(password).endsWith(user.getPasswordMd5CheckSum())) { return user; } } returnnull; } }
@Test publicvoidtestLoginOne() { // Create a stubbing and verify the expected behavior. StringmockedUserName="max"; StringmockedPassword="???"; StringmockedEmail="mocked@mocki.to"; StringmockedPasswordMd5Checksum="This is a mocked user..."; Mockito.when(this.loginService.login(mockedUserName, mockedPassword)).thenReturn( newUser(mockedUserName, mockedEmail, mockedPasswordMd5Checksum)); Useruser=this.loginService.login(mockedUserName, mockedPassword); Assert.assertEquals(user.getUserName(), mockedUserName); Assert.assertEquals(user.getEmail(), mockedEmail); Assert.assertEquals(user.getPasswordMd5CheckSum(), mockedPasswordMd5Checksum); }
@Test publicvoidtestLoginTwo() { Useruser=this.loginService.login("max", "password"); // The mocked "loginService" instance returns null by default(when there's no stubbing). Assert.assertNull(user); }
@Test publicvoidtestLoginThree() { LoginServicelocalLoginService=newLoginService(); Useruser= localLoginService.login("max", "password"); // A non-mocked "loginService" instance can still work as before, which means // the "@Mock" annotation only affects the class instance, not the class. Assert.assertNotNull(user); } }