1. quickstart
package lesson1_quickstart; import common.Account; import common.AccountDao; import common.AccountLoginController; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import javax.servlet.http.HttpServletRequest; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class AccountLoginControllerTest { private AccountDao accountDao; private HttpServletRequest request; private AccountLoginController accountLoginController; @Before public void setUp() { accountDao = Mockito.mock(AccountDao.class); request = Mockito.mock(HttpServletRequest.class); accountLoginController = new AccountLoginController(accountDao); } @Test public void testLoginSuccess() { when(request.getParameter("username")).thenReturn("cain"); when(request.getParameter("password")).thenReturn("123456"); Account account = new Account(); when(accountDao.getAccount(anyString(), anyString())).thenReturn(account); String login = accountLoginController.login(request); Assert.assertEquals("/index", login); } @Test public void testLoginFailure() { when(request.getParameter("username")).thenReturn("cain"); when(request.getParameter("password")).thenReturn("123456"); when(accountDao.getAccount(anyString(), anyString())).thenReturn(null); String login = accountLoginController.login(request); Assert.assertEquals("/login", login); } @Test public void test505() { when(request.getParameter("username")).thenReturn("cain"); when(request.getParameter("password")).thenReturn("123456"); when(accountDao.getAccount(anyString(), anyString())).thenThrow(UnsupportedOperationException.class); String login = accountLoginController.login(request); Assert.assertEquals("500", login); } }
package common; import javax.servlet.http.HttpServletRequest; public class AccountLoginController { private AccountDao accountDao; public AccountLoginController(AccountDao accountDao) { this.accountDao = accountDao; } public String login(HttpServletRequest request) { final String username = request.getParameter("username"); final String password = request.getParameter("password"); try { Account account = accountDao.getAccount(username, password); if (account == null) { return "/login"; } else { return "/index"; } } catch (Exception e) { return "500"; } } }
package common; public class AccountDao { public Account getAccount(String username, String pwd) { throw new UnsupportedOperationException("DB is down"); } }
package common; public class Account { }