Have you ever heard the phrase, "To study something, it's best to make it." Even though I used JUnit for business, I didn't know how it was made. Since I left the company and am in the process of changing jobs, I have time, so I decided to actually make my own version of JUnit.
I searched for the JUnit source code, but found only JUnit 4 and JUnit 5. (Other than official, there are other than JUnit4 and JUnit5.)
There are two directories under `junit4 / src / main / java /`
of JUnit4 source code.
Looking inside, it seems that different sources are stored. For the time being, I decided to refer to `` `junit```. The reason is as follows.
At first, I read the junit source one by one, but for the following reasons, I just grasped the main flow.
JUnit is executed according to the following flow. If you use it for business, the integrated development environment will do it for you. Please see JUnit's Official Page for details.
The explanation of how to create a test class and how to compile a test class is omitted.
Execute the following command.
java -cp A class that runs the required library tests(JUnit3 junit.textui.TestRunner)Tested class
The important thing is to specify the class to execute the test and the class to be tested.
How is JUnit doing the work? Is there any special mechanism? The bottom line is that you're not doing anything difficult, you're just using Reflection.
You know that class is the entry point because you have a class that runs the tests.
If you actually look at `junit4 / src / main / java / junit / textui / TestRunner.java```, there is a ``` main ()
method. So junit is simply reading the ``` main ()
`` method. I'm not doing anything special.
Now that you know the entry point, how do you execute the test method?
Various methods are called from the `main ()`
method earlier, but the ones that actually execute the methods are as follows.
junit4/src/main/java/junit/framework/TestCase.java runTest()Method
Looking at the contents, it's just `method.invoke ()`
. (method is Method type)
This is a feature of Reflection.
Reflection is simply a feature that allows you to read and execute class and method information at runtime. It was a long time ago, but it was famous as black magic. The advantage of Reflection is that you have the flexibility to work with classes and methods. The disadvantage is the flip side of the advantage. Execution speed is slow because the JVM needs to collect information at runtime. You can also execute private methods, so if you use it incorrectly, it will be erratic.
I got the minimum knowledge needed to create JUnit above. I thought about the class I needed, assuming that it would perform the minimum functionality.
--Assert (provides assertEquals) --TestResult (hold test result) --TestRunner (entry point) --TestCase (test class superclass)
See GitHub. Currently, the class structure is slightly different.
The good points to try are as follows.
Recommended Posts