I will transcribe how to write the Junit 5 test class that I practiced in the past as a memorandum. I hope it will be helpful to everyone.
First of all, the place to put the test class.
Keep the test class separate from the product class and folder. When using Gradle, src / test / java is the standard folder.
Avoid the same name as the product class for the test class package name. However, I definitely want to link it with the test class. So, I think you don't have to use the form "test + package name to be tested".
The reason why the package name is different is that when using Spring, It is a countermeasure such as DI duplication in the test class. (Sure) With the same package name, I couldn't DI the test folder and DI for the class I wanted to test, so It is designed so that it can be distinguished from the beginning of the package name.
Don't use this too, let's use "class name to be tested + Test". If the class name is the same, it will be annoying when complementing.
Tested class
Greeting.java
public class Greeting {
public String hello() {
return "Hello";
}
public String helloWorld() {
return "Hello World";
}
}
Test class
GreetingTest.java
class GreetingTest {
@Nested
@DisplayName("method : hello")
public class Hello {
private Greeting test = new Greeting();
@Test
@DisplayName("Test case that works properly")
public void case1() {
Assertions.assertEquals("Hello", test.hello());
}
}
@Nested
@DisplayName("method : helloWorld")
public class HelloWold {
private Greeting test = new Greeting();
@Test
@DisplayName("Test case that works properly")
public void case1() {
Assertions.assertEquals("Hello World", test.helloWorld());
}
}
}
It is safe not to attach anything. If you add something like public, it will be displayed as a complement, so it is difficult to see.
The test class is divided into test classes for each method so that it is easy to see. This form makes it easy to add test cases when adding test cases.
The method name is easy to understand for the inner class name.
From experience, the method name of the test case may be longer or more appropriate. It's terribly hard to read. Therefore, if you want to give a long method name, use DisplayName firmly. Let's write the test content.
If you write Display, it will be reflected on the coverage screen, so it will be easier to understand.
The content of the test class is important, but it is also important to write it in the same way. By writing in a formal way, let's write a test class that is easy to change not only during development but also during maintenance.
Recommended Posts