====== JUnit ===== * description : JUnit에 관한 정비 기술 * author : 도봉산핵주먹 * email : hylee@repia.com * lastupdate : 2020-09-03 ===== JUnit ===== [[wiki:java:junit:JUnit A Cook's Tour|JUnit A Cook's Tour]] \\ 자바 프로그래밍 언어용 단위 테스트 프레임워크입니다. \\ [[wiki:java:junit:JUnit5|JUnit5]]\\ ===== 동작 순서(토비 스프링3) ===== - 테스트 클래스에서 @Test가 붙은 public이고 void형이며 파라미터가 없는 테스트 메소드를 모두 찾는다. - 테스트 클랙스의 오브젝트를 하나 만든다. - @Before가 붙은 메소드가 있으면 실행한다. - @Test가 붙은 메소드를 하나 호출하고 테스트 결과를 저장해둔다. - @After가 붙은 메소드가 잇으면 실행한다. - 나머지 테스트 메소드에 대해 2~5번을 반복한다. - 모든 테스트의 결과를 종합해서 돌려준다. \\ ===== 기본 사용 방법 ===== ==== 프로젝트 셋팅 ==== 1. 기본 JAVA 프로젝트 생성 > src에 "jUnitStudy" 패키지 생성 > Scoreable.java class 생성 \\ 2. src와 동일선상에 test 폴더 생성 \\ \\ ==== JUnit 테스트 클래스 생성 ==== JUnit Test Class라는 것을 eclipse에 알려주는 방법\\ {{:wiki:java:junit:junit01.png?400|}} \\ 1. Test할 class 우클릭 > New > JUnit Test Case 클릭\\ \\ {{:wiki:java:junit:junit02.png?400|}} \\ 2. 네모 박스에는 ''"class name"/src'' 로 되어있다. 이를 ''"class name"/test''로 변경해주면 test폴더 밑에 className+"Test.java"로 생성된다. \\ * 처음 추가 시 New JUnit Test Case 라는 팝업으로 라이브러리를 추가 할거냐고 묻는다. OK 눌러주면된다. Tip: 위 ''New JUnit Test Case'' 설정시에 상단에 라디오버튼이 있는데 이 중에 ''New JUnit 4 test''를 선택해 줘야한다.\\ \\ \\ {{:wiki:java:junit:junit03.png?400|}} \\ 3. 프로젝트명 우클릭 > Run As > Junit Test로 Run해 준다.\\ \\ {{:wiki:java:junit:junit04.png?400|}} \\ 4. Run하면 JUnit이라는 창에 상태가 표시된다.\\ * 빨간 막대는 error가 있다는 표시 * error 없으면 녹색표시 \\ ===== Trouble Shooting ===== > JUnit5 (X), JUnit4 (O) JUnit5는 오류가 아직 많아 안전한 JUnit4를 사용해야한다. * Java개발하는 eclipse나 IntelliJ 등등 개발 IDE에는 기본으로 포함되어있다. * 처음 설정시에는 5로 자동 설정되는 경우가 있으므로 재설정해야한다. \\ ===== Annotation ===== ^ 어노테이션 ^ 설명 ^ | @Test | 해당 Method는 Test대상 메소드임을 의미한다. | | @BeforeClass | 해당 테스트가 시작 전에 딱 한 번씩만 수행되도록 지정한다. | | @AfterClass | 해당 테스트가 끝나고 딱 한 번씩만 수행되도록 지정한다. | | @Before | 해당 테스트가 진행이 시작되기 전에 작업할 내용을 호출한다. | | @After | 해당 테스트가 진행이 끝난 후에 작업할 내용을 호출한다. | | @Ignore | TestCase를 무시할 수 있다. | ===== Assert ===== 단언 ^ assert method ^ assertThat method ^ static Import ^ 설명 ^ | assertNull(value); | assertThat(actual, nullValue); | org.hamcrest.core.IsNull.nullValue | | | assertNotNull(value); | assertThat(actual, notNullValue); | org.hamcrest.core.IsNull.notNullValue | | | assertTrue(value); | assertThat(actual, is(true)); | org.hamcrest.core.Is.is | 참이라고 가정 | | assertTrue(1 > 3); | assertThat(1, greaterThan(3)); | org.hamcrest.number.OrderingComparison.greaterThan | | | assertTrue(“abc”.contains(“d”)); | assertThat(“abc”, containsString(“d”)); | org.hamcrest.core.StringContains.containsString | | | assertFalse(value); | assertThat(actual, is(false)); | org.hamcrest.core.Is.is | 거짓이라고 가정 | | assertEquals(“expected”, “actual”); | assertThat(“actual”, is(“expected”)); | org.hamcrest.core.Is.is | 동일하다고 가정 | | assertArrayEquals(new String[]{“test1”, “test2”}, new String[]{“test3”, “test4”}); | assertThat(new String[]{“test1”, “test2”}, is(new String[]{“test3”, “test4”})); | org.hamcrest.core.Is.is | | | assertSame(expected, actual); | assertThat(actual, sameInstance(expected)); | org.hamcrest.core.IsSame.sameInstance | | | assertNotSame(expected, actual); | assertThat(actual, not(sameInstance(expected))); | org.hamcrest.core.IsNot.not, org.hamcrest.core.IsSame.sameInstance | | | assertThat \\ * 부동 소수점 비교\\ assertThat(2.32*3, equalTo(6.96))\\ -> assertTrue(Math.abs ( ( 2.32 * 3 ) - 6.96) < 0.0005)\\ * 설명 추가 가능\\ assertThat('메시지', 실제 표현식, matcher) \\ * 실패하면 스택트레이스 출력 | assertThat \\ * 부동 소수점 비교\\ assertThat(2.32*3, equalTo(6.96))\\ -> assertTrue(Math.abs ( ( 2.32 * 3 ) - 6.96) < 0.0005)\\ * 설명 추가 가능\\ assertThat('메시지', 실제 표현식, matcher) \\ * 실패하면 스택트레이스 출력 | | 명확한 값을 비교, 햄크레스트\\ * assertThat(실제 표현식, matcher)\\ matcher\\ equalTo()\\ is(true)\\ startsWith('xyz')\\ not(equalTo())\\ is(not(nullValue()))\\ is(notNullValue())\\ closeTo(, )\\ import static org.hamcrest.number.IsCloseTo.* | | 정적 임포트 사용\\ import static org.junit.Assert.*\\ import static org.hamcrest.CoreMatchers.* 햄크레스트\\ 조건이 참이 아닐경우 동작\\ 테스트는 멈추고, failure 보고 ||| | \\ ===== Tip ===== \\ ===== Related knowledge ===== ==== xUnit ==== 언어별로 있는 단위 테스팅 프레임워크를 통칭 xUnit이라 합니다. \\ > JUnit은 xUnit의 계열 중 하나 입니다. \\ \\ ^ xUnit이름 ^ 해당언어 ^ 관련 사이트 ^ | CUnit | C | http://cunit.sourceforge.net/ | | CppUnit | C++ | https://sourceforge.net/projects/cppunit/ | | PHPUnit | PHp | https://phpunit.de/ | | PyUnit | Python | http://pyunit.sourceforge.net/ | | JUnit | Java | http://junit.org/ | ===== Terms ===== FIRST(빠르고, 고립시키고, 반복 가능하며, 스스로 검증 가능하고, 적시에 사용) \\ Fast \\ Isolated \\ Repeatable \\ Self-validating \\ Timely \\ \\ A.A.A(준비, 실행, 단언) \\ Arrange \\ Act \\ Assert \\ \\ ===== Ref ===== > 자바와 JUnit을 활용한 실용주의 단위 테스트(길벗 출판사) \\ {{tag>도봉산핵주먹 주레피 JUnit junit}}