Usage of JUnit Basic

How to Use Junit

1. Calculator Example

We need two files for testing JUnit. One is Calculator.java and the other is CalculatorTest.java Let’s start to make the package and files for that.

1
2
3
4
> mkdir src/main/java/com/kidongyun
> touch src/main/java/com/kidongyun/Calculator
> mkdir src/test/java/com/kidongyun
> touch src/test/java/com/kidongyun/CalculatorTest
  • Calculator.java
1
2
3
4
5
6
7
8
9
10
11
12
13

package com.kidongyun;

public class Calculator {
public int add(int num1, int num2) {
return num1 + num2;
}

public int sub(int num1, int num2) {
return num1 - num2;
}
}

  • CaculatorTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

package com.kidongyun;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class CalculatorTest {
Calculator calculator;

@Before
public void setUp() {
calculator = new Calculator();
}

@Test
public void testAdd() {
assertEquals(30, calculator.add(10, 20));
}

@Test
public void testSub() {
assertEquals(20, calculator.sub(30, 10));
}
}

When you want to test your code like Calculator.add() or Calculator.sub(), then you can use JUnit library like CalculatorTest Code

Let’s see the code of CalculatorTest.testAdd(). It’s for Calculator.add() Code.

and assertEquals() function is for checking whether the code operate right or not, For example we hope to get 30 value when we use calculator.add(10, 20) If we get 30 from calculator.add() function then maybe testAdd() will return something means success. otherwise it may return fail.

2. Explanation of annotation

  • @Test

We usually use @Test annotation when we want to test some code. yes, Actually It’s really basic annotation in JUnit library.

  • @Test(timeout=5000)

for testing related to time, then you can use like this annotation.

  • @Test(expected=….)

whenever you encounter the error what can be predicted like try catch syntax then please use this annotation.

  • @Before

If you want to set some envrionment or code before testing, then you can use this annotation named @Before. You can initialize everything if you use before test code.

  • @After

Otherwise above annotation, If you need to arrange the code after testing, then you are able to use @After annotation.

  • @BeforeClass

It’s execute only once at the test class before test something.

  • @AfterClass

It’s execute only once at the test class after test something.

3. Explanation of function

  • assertEquals(a, b)

For checking whether object a‘s value and object b‘s value are same or not. ex) like “a”.equals(“b”)

  • assertArrayEquals(a, b)

For checking whether Array a and object b are same or not.

  • assertSame(a, b)

For checking whether object a and object b are same or not. ex) like “a” == “b”

  • assertTrue(a)

Is a true or not?

  • assertNotNull(a)

Is a null or not?

JUnit Usage you should remember

    1. Unit tesing is not about finding bugs. (단위 테스트는 버그를 찾기 위한 것이 아니다.)

Acutally Unit testing like JUnit isn’t for bugs. It’s just only for checking the functions separately. If It’s for only finding some errors, Testing all of system at a once is more effectively then unit test.

    1. Test only one code unit at a time. (하나의 테스트 케이스는 단위 기능 중 하나의 시나리오만 테스트 하라.)

the most important thing when you do Unit-Test is that you have to make the test code for only one scenario.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

function sample(param1, param2) {
return result
}

/*

param1 param2
Scenario 1. normal null
Scenario 2. null normal
Scenario 3. null null
Scenario 4. normal normal

*/

Above sample function can have 4 scenarios at least. Every test codes and Scenarios should operate independently.

    1. Don’t make unnecessary assertions. (불필요한 검증 구문을 작성하지 마라.)

Unit-Test isn’t to observe everything of the project code, So you don’t need to make the test code for all things. Otherwise Making a test code will be to throw away your precious time.

    1. Don’t use unit-test fore configuration environment settings. (시스템 설정 파일에 관한 단위 테스트를 작성하지 마라.)
    1. Naming of Unit-Test should be clearly and consistently. (단위 테스트 케이스의 이름은 명확하고 일관데게 테스트의 의미를 반영해야 한다.)
    1. Let’s write the independent test code about external system or service more earlier than it isn’t. (외부 시스템이나 서비스에 대한 의존성이 가장 낮은 메소드들에 대해 테스트를 먼저 작성하자.)
    1. Create Unit-Test using target exceptions if you can. (예상된 예외 사항을 테스트하는 단위 테스트 코드를 작성하라.)
    1. Put the parameters keeping the order properly. (검증 구문 파라미터들은 적합한 순서대로 배치하라.)
    1. Test code should be separated from the production. (테스트를 위한 코드는 제품 코드에서 분리되어야 한다.)
    1. Don’t print out anything in the Unit-Test code. (테스트 코드 내에서 아무것도 출력하지 마라.)
    1. Don’t use static members for the test class. If you used then re-initialize for each test. (정적 변수를 테스트 클래스에 사용하지 마라. 만약 사용했다면 각 테스트 케이스 실행시마다 재 초기화해라.)
Share