[JAVA] How to use JUnit (beginner)

About how to use JUnit. JUnit is an older version, as I'm writing it to disseminate test code in the workplace.

Introduction

Why you want to introduce the habit of writing tests

I don't think it will be effective as soon as I start writing test code, but I hope to improve it little by little. When I write the test code, I think that the story comes out as man-hours ... or speed ..., but it takes time until I get used to it, and if I actually start writing, I will go back. I think that there are many good things as a whole because it is easy to improve the quality because it is tested against my own code.

There are various articles about the usefulness of the test code, so please have a look there.

reference

The story of introducing tests in lawless areas where there were no tests and increasing the development speed by 1.7 times How to fight technical debt

Then how far do you aim?

I'd like to discuss this area in various ways, but personally I haven't aimed for 90% or more of coverage so far, so I'll make it a habit for the time being and prepare for future framework transitions. I'm thinking.

This is what I want to do in the near future.

Execution environment

Simple test sample

To get a rough idea of the test, here's a simple test example.

Production code


public class HelloJunit {

	public String sayHello() {
		return "Hello";
	}
}

Test code


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

import org.junit.Test;

public class HelloJunitTest {

	@Test
say public void Hello() {
		HelloJunit helloJunit = new HelloJunit();
		assertThat(helloJunit.sayHello(), is("Hello"));
	}
}

Test code explanation

name of the class

For the test class name, set the name obtained by adding Test to the class name of the production code to be tested. This will recognize the class under test and the test code as a testing pair.

Test method

Create a method for testing. If possible, create one method for each case in the test. (Do not create multiple tests in the same method) Also, set the method name in Japanese so that the contents of the test case can be easily understood.

By adding @ Test annotation to the method, it will be executed as the method to be tested when the test is executed.

assertThat / is Use ʻassertThat when comparing values. The usage of assertThat is ʻassertThat (expected value, Matcher method (measured value));.

The ʻis method makes a comparison using the ʻequals of the target object. This time the "Hello" strings are compared and true, so the test succeeds.

Execution result

If the graph on the right is green, you are successful. For details, check the execution, error, and failure on the left.

スクリーンショット 2019-05-19 15.14.26.png

If it fails

If the test fails, the details of the error will be output on the log. (The graph on the right turns red) A concrete comparison result (value) is displayed in the failure trace, so it is necessary to correct it while referring to this.

スクリーンショット 2019-05-19 15.16.32.png

Annotation

Test Annotation for JUnit to recognize as a test method. If this annotation is attached, it will be tested. The method must be public void.

Test annotation


@Test
say public void Hello() {
	helloJunit = new HelloJunit();
	assertThat(helloJunit.sayHello(), is("Hello"));
}

Before Methods with this annotation are executed before running the test. It is used to perform some common processing.

In the following example, the process of instantiating the test target class that is commonly used is included.

Before annotation


@Before
public void setUp() {
	helloJunit = new HelloJunit();
}

After The method with this annotation is executed last after all the tests have been performed. There is a usage method such as allocating an external resource with Before and releasing it with After.

After annotation


@Before
public void setUp() {
	helloJunit = new HelloJunit();
	File file = new File(FILE_PATH);
	try {
		filereader = new FileReader(file);
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	}
}

@After
public void termDown() {
	try {
		filereader.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

Ignore Methods with this annotation will be skipped even with the Test annotation. It is used when you do not want to test temporarily for some reason.

@Ignore
@Test
say public void Hello() {
	helloJunit = new HelloJunit();
	assertThat(helloJunit.sayHello(), is("Hello"));
}

Matcher API

is It is compared using the equals method. If you set a primitive type, it will be changed to a wrapper class and compared with equals.

is


@Test
Try public void is() {
	assertThat("Hello", is("Hello"));
	assertThat(1, is(1));
}

not not is a test to make sure the result of the comparison is false. You can use ʻassertThat ("Hello", not ("bye")); , but it is better to use ʻis (not (~)) so that it is correct in English.

not


@Test
Try public void not() {
	assertThat("Hello", is(not("bye")));
}

null value Make sure it's still Null. Conversely, there is also notNullValue.

nullValue


@Test
try public void nullValue() {
	assertThat(null, nullValue());
}

instanceOf(isA) Make sure the types are the same.

instanceOf


@Test
Try public void instanceOf() {
	assertThat("Hello", instanceOf(String.class));
}

sameInstance Make sure they are the same instance.

sameInstance


@Test
Try public void sameInstance() {
	assertThat("Hello", sameInstance("Hello"));
}

allOf If all Matchers in allOf are true, it succeeds.

allOf


@Test
Try public void allOf() {
	assertThat("Hello", allOf(not("bye"),sameInstance("Hello")));
}

Other

If the version of JUnit is a little higher, there are useful ones such as hasItem, hasItems and startsWith, but ... For more information, please refer to here.

Check for exceptions

This is a way to test that an exception is output. There are two ways to test.

  1. Set target in Test annotation
  2. Try catch and check

Below is a sample production code.

Production code


public class HelloJunit {
	public void throwException() {
		throw new IllegalArgumentException("Illegal argument");
	}
}

Check with Test annotation

It is possible to test by specifying the class in which Exception occurs by using ʻexpected` in the Test annotation.

Check with Test annotation


@Test(expected = IllegalArgumentException.class)
Check public void Exception with Test annotation() {
	helloJunit.throwException();
}

Catch and check

You can compare the code under test by try catch. With this method, it is possible to verify the message when an exception occurs.

catch and check


@Test
Check public void Exception with catch() {
	try {
		helloJunit.throwException();
	} catch (IllegalArgumentException expected) {
		assertThat(expected.getMessage(), is("Illegal argument"));
	}
}

Reference material

Other Qiita articles that look good [Notes on how to use the methods defined in Hamcrest's Matchers](https://qiita.com/opengl-8080/items/e57dab6e1fa5940850a3#isin--Check that it matches either the array or the element specified in the collection To do)

Recommended Posts

How to use JUnit (beginner)
How to use JUnit 5
[Creating] How to use JUnit
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 Twitter4J
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 hashes
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 java class
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 rails join
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
How to use Java variables
[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
[Beginner] Discover the N + 1 problem! How to use Bullet
[Beginner] How to use devise Change settings from introduction