17. 단위 테스트 (Unit Test) 전체 기능이 아닌 일부 범위만 테스트 주로 클래스의 메서드가단위 테스트의 대상 단위 테스트 예, DB 연동 처리(DAO) 클래스의 select() 메서드 테스트 회원 가입 Service 클래스의 regist() 메서드 테스트 Controller Service DAO 통합테스트 (Integration Test) 단위테스트 (Unit Test)
18. 단위 테스트 프레임워크 기본 프레임워크 JUnit (*) TestNG JUnit테스트 예 public class CryptoTest { @Test public void test() { String source = "madvirus,최범균,전략기술팀"; String encrypted = Crypto.encrypt(source); String expectedEnc = "UiDWVjs050cbZpQDOPV….."; assertEquals(expectedEnc, encrypted); assertFalse(source.equals(encrypted)); System.out.println(encrypted); String decrypted = Crypto.decrypt(encrypted); assertEquals(source, decrypted); } }
23. 인터페이스에 대고 개발 public class Service { private Dao dao; public intsomeMethod() { intval = dao.select(); return val + 1; } public void setDao(Dao dao) { this.dao = dao; } } public interface Dao { int select(); }
24. 의존 대상을 Mock으로 대체 Mock을 이용한 단위 테스트 실제 구현 대신 Mock 구현 사용 예, public class ServiceTest { @Test public void testSomeMethod() { MockDaodao = new MockDao(); Service service = new Service(); service.setDao(mockDao); int result = service.someMethod(); assertEquals(2, result); } } public class MockDao implements Dao { public int select() { return 1; } }
25. Mock 생성 Mock을 생성해주는 라이브러리 Mockito, Spring Test, easyMock, jMock등 Mock 이용 테스트 샘플 public void setUp() { authenticator = mock(Authenticator.class); // mock 생성 loginController = new LoginController(); loginController.setAuthenticator(authenticator); } @Test public void login() { HttpServletRequestrequest = new MockHttpServletRequest(); // 웹 요청 Mock Authentication authentication = mock(Authentication.class); when(authenticator.authenticate(Mockito.<AuthenticationRequest> anyObject())) .thenReturn(authentication); ModelAndViewmav = loginController.login(request, "id", "password"); // 테스트 assertEquals(LoginController.DEFAULT_SUCCESS_VIEW_NAME, mav.getViewName()); verify(authenticator).authenticate(Mockito.<AuthenticationRequest>anyObject()); }
26. 내용 정리 테스트가 용이하도록 테스트하기 쉬운 크기로 클래스를 잘게 나눔 인터페이스에 의존해서 테스트 용이하도록, Mock을 이용한 테스트 덤으로 병행 개발 가능 테스트 프레임워크를 사용 JUnit, Mockito, Spring Test 짧은 주기로 리듬감 있는 개발 실현!
27. 앞으로…. 숙제는 단위 테스트 습득 JUnit세미나 통합 테스트 기법 습득 Spring이 제공하는 테스트 기법 DB 테스트 기법 습득 DbUnit세미나 웹 기능 자체의 테스트 자동화 Selenium 세미나