Unit Testing in Java

Unit testing Isolates one piece of code and verifies that piece is working correctly. In Java that piece of code is going to be a class or a function inside of the class.

Unit Testing With Maven

If you are using maven and want to test your code with unit testing I recommend Junit. If you want to use Junit also just add it to the dependencies in your project(same thing with gradle).

If you are using intellij there is a shortcut for it, just click inside of the function/class you want to create test for and hit ctrl + shift + t , and then click to create new test option.

It will automatically import everything from the Assertions package click here to learn more about Assertions package.

Any test you created will be in the exact package structure as your tested code

in Junit a test is a just method you label with `@Test` annotation. If it is your first test in the page it will import `jupiter.api.Test`

The optimal way of testing is to test for a single scenario per test. This way you can identify the parts you have to look at again easily.

Running tests with coverage

Let’s say you start writing your tests for a function and saw that it all passes, works without a problem. Are you feeling happy, are you feeling like you are a coding god, and never going to die? Well you are probably not, and you probably forgot to use Coverage in your tests which shows you what percentage of the written code you actually test for in IntelliJ. To use it just click the option run with coverage from the left side run button. 🙂