JUnit & AssertJ

23

Transcript of JUnit & AssertJ

Page 1: JUnit & AssertJ
Page 2: JUnit & AssertJ
Page 3: JUnit & AssertJ
Page 4: JUnit & AssertJ
Page 5: JUnit & AssertJ
Page 6: JUnit & AssertJ
Page 7: JUnit & AssertJ

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.12</version>

<scope>test</scope>

</dependency>

Maven

Page 8: JUnit & AssertJ

@Slf4j

public class Calculator {

/**

* 더하기*

* @param nums 더하기할숫자들* @return 합*/

public double add(double... nums) {

log.trace("더하기... nums={}", nums);

double sum = 0.0;

for (double n : nums) {

sum += n;

}

log.debug("합={}", sum);

return sum;

}

}

@Slf4j

public class CalculatorTest {

@Test

public void testAdd() {

Calculator calculator = new Calculator();

Assertions.assertThat(calculator.add(1, 2)).isEqualTo(3);

}

}@Slf4j

public class CalculatorTest {

@Test

public void testAdd() {

Calculator calculator = new Calculator();

assertThat(calculator.add(1, 2)).isEqualTo(3);

assertThat(calculator.add(-1, -2)).isEqualTo(-3);

assertThat(calculator.add()).isEqualTo(0);

}

}

Page 9: JUnit & AssertJ
Page 10: JUnit & AssertJ
Page 11: JUnit & AssertJ

Test Class

@Test

@Test

@Test

@Before

@BeforeClass

@AfterClass

@After

1

2

3

45 86

9

7 10

11

Page 12: JUnit & AssertJ

@Test(expected = AssertionError.class, timeout = 1000L)

public void testAddException() {

Calculator calculator = new Calculator();

assertThat(calculator.add(1, 2)).isEqualTo(5);

}

Page 13: JUnit & AssertJ

@Slf4j

public class JUnitAnnotationTest {

private static Calculator calc;

@BeforeClass

public static void setupClass() throws Exception {

log.debug("Before Class...");

calc = new Calculator();

Thread.sleep(100L);

}

@Before

public void setup() {

log.debug("Before ...");

}

@After

public void cleanup() {

log.debug("@After...");

}

@AfterClass

public static void cleanupClass() {

log.debug("After Class...");

}

@Test

public void test1() {

log.debug("test1");

assertThat(calc).isNotNull();

}

@Test

public void test2() {

log.debug("test2");

assertThat(calc).isNotNull();

}

}

2016-01-15 11:40:55,935 DEBUG k.k.java.study.JUnitAnnotationTest.setup : Before ...

2016-01-15 11:40:55,935 DEBUG k.k.java.study.JUnitAnnotationTest.test1 : test1

2016-01-15 11:40:55,960 DEBUG k.k.java.study.JUnitAnnotationTest.cleanup : @After...

2016-01-15 11:40:55,961 DEBUG k.k.java.study.JUnitAnnotationTest.setup : Before ...

2016-01-15 11:40:55,962 DEBUG k.k.java.study.JUnitAnnotationTest.test2 : test2

2016-01-15 11:40:55,962 DEBUG k.k.java.study.JUnitAnnotationTest.cleanup : @After...

Before Class...2016-01-15 11:40:55,831 DEBUG k.k.java.study.JUnitAnnotationTest.setupClass : Before Class...

2016-01-15 11:40:55,962 DEBUG k.k.java.study.JUnitAnnotationTest.cleanupClass : After Class...

Page 14: JUnit & AssertJ
Page 15: JUnit & AssertJ
Page 18: JUnit & AssertJ

<dependency>

<groupId>org.assertj</groupId>

<artifactId>assertj-core</artifactId>

<version>3.2.0</version>

<scope>test</scope>

</dependency>

Maven

Gradle

testCompile ‘org.assertj.assertj-core:3.2.0’

Page 19: JUnit & AssertJ

Import Assertions class

import static org.assertj.core.api.Assertions.*;

import static org.assertj.core.api.Assertions.assertThat; // Main Assertion

import static org.assertj.core.api.Assertions.atIndex; // 리스트검증import static org.assertj.core.api.Assertions.entry; // Map 검증import static org.assertj.core.api.Assertions.tuple; // 클래스에서속성추출시사용import static org.assertj.core.api.Assertions.fail; // 예외검증시사용import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;

import static org.assertj.core.api.Assertions.filter; // 컬렉션필터링import static org.assertj.core.api.Assertions.offset; // 부동소숫점수형관련import static org.assertj.core.api.Assertions.anyOf; // 컨디션적용import static org.assertj.core.api.Assertions.contentOf; // 파일관련검증

Page 20: JUnit & AssertJ

assertThat(cfg.getDatabase()).isNotNull();assertThat(cfg.getDatabase().getDriverClass().isPresent()).isTrue();assertThat(cfg.getDatabase().getJdbcUrl().isPresent()).isTrue();

Offset<Double> offset = Assertions.offset(1.0e-8);

assertThat(valueOf("142.milligrams").inGram()).isEqualTo(milligram(142).inGram(), offset);assertThat(valueOf("0.1.gram").inGram()).isEqualTo(gram(0.1).inGram(), offset);assertThat(valueOf("10000.1.gram").inGram()).isEqualTo(gram(10000.1).inGram(), offset);assertThat(valueOf("78.4.kilogram").inGram()).isEqualTo(kilogram(78.4).inGram(), offset);

assertThatThrownBy(() -> valueOf("100.bottles")).isInstanceOf(NumberFormatException.class);

assertThatThrownBy(() -> valueOf("100 gram")).isInstanceOf(NumberFormatException.class);

assertThatThrownBy(() -> valueOf("100.0.0.0.gram")).isInstanceOf(NumberFormatException.class);

Page 21: JUnit & AssertJ

import static org.assertj.core.api.Assertions.assertThat;

import static org.assertj.core.api.Assertions.fail;

import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;

// ... 생략

assertThat(fellowshipOfTheRing).hasSize(9);

// 일반적으로예외발생에대한검증처리try {

fellowshipOfTheRing.get(9); // 예외발생!!!

// 여기까지코드가오는것은기대했던예외가발생하지않았다는뜻! 검증실패fail("IndexOutOfBoundsException expected because fellowshipOfTheRing has only 9 elements");

} catch (IndexOutOfBoundsException e) {

assertThat(e).hasMessage("Index: 9, Size: 9");

}

// 주의점 : Throwable 로 catch 하면안된다.

// 그러면 fail로발생한 AssertionError 도 catch 해서검증성공으로인식해버린다.

// 다른방식try {

fellowshipOfTheRing.get(9); // 예외발생!!

// 기대했던예외가발생하지않았다는뜻! 검증실패failBecauseExceptionWasNotThrown(IndexOutOfBoundsException.class);

} catch (IndexOutOfBoundsException e) {

assertThat(e).hasMessage("Index: 9, Size: 9");

}

With Java 7

Page 22: JUnit & AssertJ

@Test

public void testException() {

assertThatThrownBy(() -> { throw new Exception("boom!")

}).isInstanceOf(Exception.class)

.hasMessageContaining("boom"); }

With Java 8

@Test

public void testException() {

// given some preconditions

// …

// when

Throwable thrown = catchThrowable(() -> { throw new Exception("boom!") });

// then

assertThat(thrown).isInstanceOf(Exception.class) .hasMessageContaining("boom"); }

With Java 8 BDD

Page 23: JUnit & AssertJ

// 두인스턴스가같은배우이고, 속성중종족값만같은경우...

// fredo 와 sam 은다른사람이지만같은호빗족이다.

assertThat(frodo).isNotEqualTo(sam);

// raceComparator 가 Comparator<AClass> 이면서 race 값만비교하는경우assertThat(frodo).usingComparator(raceComparator).isEqualTo(sam);

// 절대반지그룹에간달프는속해있지만, 사우론은아니다assertThat(fellowshipOfTheRing).contains(gandalf).doesNotContain(sauron);

// 하지만종족을비교하는 raceComparator 를사용하면사우론도간달프와같은 Maia 종족이다.

assertThat(fellowshipOfTheRing)

.usingElementComparator(raceComparator)

.contains(sauron);

usingElementComparator(Comparator) example:

usingComparator(Comparator) example: