Debug JUnit Tests using IDE
Introduction
In this tutorial, we will learn how to debug Calculator JUnit Tests using IDE like Eclipse. We would consider the Calculator JUnit Project and the tests that test the Calculator Java class. Follow the links for the basic setup of the JUnit Calculator Test project in Eclipse IDE.
Creating a Maven Project
https://www.testingdocs.com/create-quickstart-maven-project-in-eclipse-ide/
Calculator Example
https://www.testingdocs.com/junit-calculator-test-case-example/
Failing Test
Let’s make a test fail and try to debug the failing test in order to fix the test method. We will seed a fault in the test, and assume that the test is false positive and there is no bug in the application. Sometimes, it might not be true and the failing test might be a valid application bug, in that case you may need to log the issue in the Bug tracker application.
public void testAdd() { int a = 15; int b = 21; int expectedResult = 35; long result = objCalcUnderTest.add(a, b); Assert.assertEquals(expectedResult, result); }
This test would fail with the trace:
java.lang.AssertionError: expected:<35> but was:<36>
at org.junit.Assert.fail(Assert.java:91)
Steps to Debug
Launch Eclipse IDE.
Open the Calculator Project.
Open the Junit Test case which has the @Test annotated methods.
Set Breakpoint
Set Breakpoint on the statements that throw error/ exceptions etc.
To set a breakpoint, Right-click and choose Toggle breakpoint.
To Debug the JUnit Test, use the below option:
Right Click >> Debug As >> Junit Test.
Analyze
Analyze the variables, values, calculations, reference variables, etc in the debug window. Find out the root causes of errors, exceptions, etc.
Fix the tests based on your observations.
We can step into, step over multiple breakpoints during the debug session.
Fix
Based on the analysis, fix the test. In this case, though we have seeded a fault in the test, the expected Result is wrong. We have mistaken that
15 + 21 as 35 expected result which is wrong. Make the expected result 36 to fix the test. We can debug the tests for exceptions, erroneous expectations, variable watch etc.
JUnit Tutorial on this website :
https://www.testingdocs.com/junit-tutorial/
More information on JUnit can be found on the official website: