Unit Testing in Java

Beknazar
4 min readDec 20, 2021

--

Every program needs to be tested. There are many types of testings out there. Today we are going to talk about unit testing.

  1. Unit Testing.
  2. JUnit.
  3. TDD.

Unit Testing

The software consists of many units with specific logic. Unit testing is a type of testing that tests each unit separately to verify that individual parts work correctly. The unit can be represented as a module, class, and function. Most of the time unit testing is done at the functional level. Basically, we test our methods(functions) to work as expected in our source code.

Unit testing is a set of automated test cases. Usually, it’s in the same source project and created by the developers themselves.

Let’s see how we can do unit testing without using any ready solution libraries.

We would just use our method with different arguments and see if it’s returning the correct output. It’s not really automated every time we run this code we need to look at the output and see if it printed correctly.

We need something to validate the output and we need many other features to create robust automated test suites.

Make changes fearlessly. Set of unit tests lets us make changes without risking breaking existing-working functionalities(if a change breaks something, the test suite will catch it and we can apply the fix).

JUnit

JUnit is one of the libraries for unit testing in Java.

  • There is no main method. JUnit provides its own run engine.
  • We have separate test cases. The test case in JUnit is represented by a void method tagged with @Test annotation.
  • Most of the test cases will have input, actual results, expected results. Each test case should have assertions to validate the actual result with the expected result.

Let’s talk about where we should have our unit test suite.

We keep our unit test classes under the test folder.

By following Maven structure, the actual source code of the application goes:
src/main/java

And the testing code goes:
src/test/java

We will not go in-depth into JUnit. If you want to learn more please go to their official docs.

Test-driven development

I would like to mention TDD in this article because it became a big part of software development. In TDD, we write our test cases first and then we implement the actual functionality.

This is a sequel of TDD flow based on the book Test-Driven Development by Example:
1. Add a test.
2. Run all tests. The new test should fail for expected reasons.
3. Write the simplest code that passes the new test.
4. All tests should now pass.
5. Refactor as needed, using tests after each refactor to ensure that functionality is preserved.
Repeat.

That’s all for this article. Happy codings!

The resources and links used in this article:

--

--

Beknazar
Beknazar

No responses yet