[JAVA] [Creating] How to use JUnit

What is JUnit

"JUnit" is a framework for Java unit testing. You can verify that it works correctly by writing a unit test.

Test rules in JUnit

--If the class name to be tested is "Xxx", the test class name will be "XxxTest". --If the method name to be tested is "Yyy", the test method name will be "testYyy". --Add annotation "@Test" to the test method. Make it "public void" --The test method is "assertThat (actual value, is (expected value));" --Write code that makes "prerequisites, execution, verification" easy to understand

Basic usage

The basic usage is as follows.

Sample.java


public class Sample {
  public static int toDouble(int num) {
    return num * 2;
  }
}

Here's a JUnit test for the sample above:

SampleTest.java


import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;

public class SampleTest {
  @Test
  public void testToDouble() {
    int actual = Sample.toDouble(10);
    int expect = 20;
    assertThat(actual, is(expect));
  }
}

If it does not return the expected value, the test will fail as follows:

java.lang.AssertionError:
Expected: is <21>
     but: was <20>

Temporarily ignore the test: @ignore

You can temporarily ignore the test by giving @Ignore.

@Ignore @Test
public void doSomething() { /* ... */ }

Recommended Posts

[Creating] How to use JUnit
How to use JUnit 5
How to use JUnit (beginner)
How to use Map
How to use rbenv
How to use letter_opener_web
How to use with_option
How to use fields_for
How to use java.util.logging
How to use map
How to use collection_select
How to use active_hash! !!
How to use MapStruct
How to use hidden_field_tag
How to use TreeSet
[How to use label]
How to use identity
How to use Dozer.mapper
How to use Gradle
How to use org.immutables
How to use java.util.stream.Collector
How to use VisualVM
How to use Map
Notes on how to use each JUnit Rule
[Java] How to use Map
How to use Chain API
[Java] How to use Map
How to use Priority Queuing
[Rails] How to use enum
How to use java Optional
How to use Ruby return
[Rails] How to use enum
How to use @Builder (Lombok)
[Swift] How to use UserDefaults
How to use Swift UIScrollView
How to use Big Decimal
[Java] How to use Optional ②
[Java] How to use removeAll ()
How to use String [] args
[Java] How to use string.format
How to use Java Map
Ruby: How to use cookies
How to use dependent :: destroy
How to write Junit 5 organized
How to use Eclipse Debug_Shell
How to use Apache POI
[Rails] How to use validation
[Rails] How to use authenticate_user!
[Rails] How to use "kaminari"
How to use GC Viewer
[Java] How to use Optional ①
How to use Lombok now
How to migrate from JUnit4 to JUnit5
[Rails] How to use Scope
How to use the link_to method
[Rails] How to use gem "devise"
How to use Lombok in Spring
How to use StringBurrer and Arrays.toString.
How to use arrays (personal memorandum)
How to use Java HttpClient (Get)
How to use scope (JSP & Servlet)