Unit Testing in Java

Unit Testing in Java | We will discuss what is unit testing, how to perform unit testing using JUnit, what are different tools available for testing in Java, etc. Also see:-

  • Unit Testing: The test done by the programmer on their own piece of code is called unit testing.
  • Peer Testing: The unit testing done by one programmer’s code/task by his colleague programmer is called peer testing.

Testing means matching expected results with actual results. If matched then the test result is positive (test succeeded), if not matched then the test result is negative (test failed). Development and unit/peer testing should be done continuously by the programmer until test results are positive.

Business analyst gives design documents/user stories, the developer develop the code, performs the unit/peer testing, and commits the code to the Code repository (like GIT/SVN) when test results are positive. In unit/peer testing, entire projects will not be tested instead only one task will be tested. Testers/QA teams take care of the testing of the entire project.

Different types of testing done by developers:-

  • Unit testing
  • Peer testing
  • Integration testing (talks about modules/apps integration)

Different types of testing done by testers:-

  • Performance test
  • Navigation test
  • User experience test
  • System test
  • Load test
  • Functional test
  • Sanity test, and etc.

Unit testing can be done in two ways:-

  • Manual Unit Testing
  • Automated Unit Testing

Limitation of manual unit testing:-

  • No productivity because it takes time.
  • Writing test reports manually is a complex process (Excel sheet report).
  • Presenting test plans/test cases to TL/superior is a complex process.
  • Test regression (repeating the test) is very complex.

To overcome these problems, we can take the support of Unit testing automation tools like JUnit, HttpUnit (for web applications), Mockito, TestNG, and others in Java. For HttpUnit, Mockito, and TestNG tools JUnit is the base tool. All these are Java-based Unit testing tools.

In the test results we can see:-

  • Success: Expected results are matched with actual results.
  • Failures: Expected results are not matched with actual results.
  • Errors: Unanticipated/unexpected exceptions have come while testing the code.

What is the difference between failure and error in testing? Failure means the actual code has given some result but the result does not match the expected result. Whereas error means the actual code has not given any result rather it has thrown some exception.

While working with Junit we can see 3 main components:-

  • Service class/Main class:- Class to be tested.
  • Test case Class:- The class that contains test methods.
  • Test Suite: It allows to combine multiple test case classes to generate the test report. It is optional.

In a project, there can be 1 or more service classes/main classes and test case classes, but Test Suite can be 0 or 1. We can run each test case class manually to generate the test report. But if we want to get test reports of all the classes together then take the support of the Test Suite class.

JUnit 5 contains 3 runtime libraries:-

  • JUnit Jupiter: JUnit5 libraries.
  • JUnit Vintage: JUnit 3/4 libraries (for backward compatibility)
  • JUnit Integrations: To allow JUnit integration with TestNg, Mockito, and etc.
JUnit 5 Architecture-diagram knowprogram

The junit-platform-engine is responsible for loading test case classes, creating objects for them, and calling the test method. The junit-platform-launcher helps different IDEs, tools like Maven, etc to search and get junit-platform-engine.

JUnit5 Jupiter API given following which we use in the development of TestCase classes and test methods:-

  • Annotations
  • Assertion API (Gives Assertions.assertXyz() static methods to match actual results with expected results and generate test reports).

JUnit Annotations:-

  • @Test
  • @DisplayName
  • @BeforeEach
  • @AfterEach
  • @BeforeAll
  • @AfterAll
  • @Disabled
  • @TestMethodOrder
  • @RepeatedTest
  • @Tag
  • @ParameterizedTest
  • @ValueSource
  • @NullSource
  • @EmptySource
  • @NullAndEmptySource

The following are the most used Assertion methods, they have multiple overloaded forms. They all are static methods:-

  • fail
  • assertTrue
  • assertFalse
  • assertSame
  • assertNotSame
  • assertNull
  • assertNotNull
  • assertEquals
  • assertNotEquals
  • assertArrayEquals
  • assertAll

Naming conventions for test class and method names

Generally, the test case class name starts or ends with the “Test” word and all methods generally begin with the “test” word. BankService (main class) => TestBankService (test case class name).

  • float calcSimpleInterest() => void testCalSimpleInterest()
  • float getBalance() => void testGetBalance()

We write multiple forms of these test methods to test the main method or service method from multiple angles. In test case classes, for each business/service method we need to write a variety of test methods but not to increase the number of test methods. For example in the LoginApp code possible test methods/test plans:-

  • Test with valid credentials
  • Test with invalid credentials
  • Test with no credentials

In the sum logic of two numbers, possible test methods/plans:-

  • Test with positive
  • Test with negative
  • Test with mixed values
  • Test with zeros
  • Test with floating points
  • Test with chars/strings

Create a Maven project in Eclipse IDE as the standalone project as follows:- Create a new Maven project => Select archetype: maven-acrchetype-quickstart of org.apache.maven.acrchetype => Group Id: com.knowprogram, Artifect Id: JUnitDemo. Open pom.xml and change the maven.compiler.source and maven.compiler.target to your workspace available Java version. Then right click => maven => update project.

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>11</maven.compiler.source>
  <maven.compiler.target>11</maven.compiler.target>
</properties>

Remove the existing Junit dependency and add JUnit Jupiter Engine in pom.xml in dependencies:-

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.10.2</version>
    <scope>test</scope>
</dependency>

After adding the dependencies, right-click on the project => maven => update project. The main/service classes are placed inside the src/main/java folder whereas test case classes/Test Suite classes are placed inside the src/test/java folder.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *