Unit Testing using JUnit and Mockito
Introduction to Unit testing
What is Unit testing?
Unit testing is a process that is used to verify a unit or unit’s functionality. This step helps in the estimation of the codes by other team members and also creates a record of all necessary information including errors that occur. It provides an opportunity for the developer to fix errors before it becomes a problem with other modules. The code is exercised by making small modifications instead of adding many new lines in order to cover all scenarios and make sure that there are no loopholes in the program.
Unit Testing is the software testing process where a set of software program components(methods) or modules are tested individually. This technique effectively checks the implementation of the functionality and the accuracy of a section of code by using stubs, mock objects, dependencies, and unit testing frameworks.
Importance of Unit testing
Why do we need Unit testing?
- Reducing bug fixing costs.
- Validating and correcting the bugs in the early stages.
- Makes the debugging process simple and smooth.
- Safe code refactoring.
- Improves the Quality of Code.
Qualities of UTC and best practices while writing the UTCs :
- The code should be strong and loosely coupled.
- Unit tests are repeatable and scalable.
- Write isolated tests.
- Unit tests should be automated.
- Test One Scenario Per Test.
- Write readable, simple Tests.
- “Test-everything-that-can-possibly-break” programming strategy.
- Should follow AAA rule:
- Arrange: Do all the setup(creating mock objects etc,) and configurations to test the method/system.
- Act: Execute the action to perform the test.
- Assert – Verify the functionality of the method/system.
Unit Testing Frameworks
UnitTest Framework is a testing methodology by which individual units of source code, such as class, methods, and functions are tested to determine whether they perform their functionality properly or not. It also includes code coverage and code quality and good coding practices.
There are several UnitTest frameworks available as per the different programming languages. For example:
1. JUnit:
-
-
- Open-source unit testing framework for JAVA
- Supports the core concept of “first testing then coding”
- Annotation-based unit tests.Ex : @Test, @Before, @after etc..
- Supports various build tools like ANT, Maven, etc.
-
2. TestNG
-
- open-source automation testing framework for JAVA
- designed for Java Programming language
- supports concurrent testing and offers annotation support
3. Embunit
-
- an open source unit testing framework for C/ C++
4. HtmlUnit
-
- open-source unit testing framework for HTML
JUnit
JUnit: A unit testing framework that is extensively used to test the code written in JAVA. It is used to verify the implementation of the functionality of the modules and check whether the requirements have been met or not.
Some salient features of JUnit :
- Test setup and tearDown: Setup and teardown the context before and after running the test respectively.
- Asserts: Specify the expected output and compare it with the received output.
- Exception Testing: Tests and verifies whether an exception was thrown.
- Test Suits: JUnit test cases are organized into test suites for better management.
- Integration with popular build Systems: Integrates with the most popular build systems for java, including ANT and Maven.
Some frequently used annotations and Assert statements in JUnit :
- @Test: This is the test method to run, Return Type: public void
- @Before: Run before @Test, Return Type: public void
- @After: Run after @Test, Return Type: public void
- @BeforeClass: Run once before any of the test methods in the class, Return Type: public static void
- @AfterClass: Run once after all the tests in the class have been run, Return Type: public static void
- @Ignore: Blocks the test case execution.
Sample Test Class :
Output :
Mockito
What is Mockito?
- An open source mocking framework.
- Uses mock testing strategy, uses substitutes of objects to validate the code.
- Simple coding language.
What is Mocking?
- Based on the concept of a mock object (dummy object) that replaces the real objects.
- Tests the objects and methods with dependencies.
What are the different phases of Mocking?
- Stubbing: It specifies how the object will behave when the object is involved in the interaction.
- Expectation : Set an object such that it tells the expectations when the test is executed.
- Verification: Confirms that expectations have been met.
How to implement the Mockito in JUnit?
There are three steps to implement the Mockito in JUnit and these steps are as follows:
- Creating mock object
- Using stubs to set the expectations.
- Verifying using mockito.
1. Creating mock object :
- Create mock objects in JUnit by Using:
- Static mock() method call
- @Mock annotation
- A mock object is created and used to test the service
2. Using stubs to set the expectations.
- Create a stub and pass an argument to the method as a mock.
- Use the anyInt(), any(), anyString () respectively as per argument needed.
- For stubbing Void method calls :
- When() method cannot be used.
- Use doReturn(result).when(mock_Object).void_method_Call()
- Exceptions using thenThrow() or doThrow()
3. Verifying using mockito.
- Use verify() method to check whether the set expectations are met.
- Verify can check the behavior of the method like method invocations happened twice/once, multiple times or never.
Sample test case implementing Mockito in JUnit:
Some important Annotations of Mockito:
- @spy: Partial mock, which will track the interactions with the object like a mock.
- @Mock: create a mock object of a class or an interface.
- @InjectMock: inject mocked dependencies in the annotated class mocked object.
Assert Class:
It is a JUnit class that consists of a set of assertion methods useful for writing tests. Only failed assertions are recorded. These methods can be used directly.
Example :
assertArrayEquals(boolean[] expected, boolean[] actuals) : Asserts that two boolean arrays are equal.
assertArrayEquals(byte[] expected, byte[] actuals) : Asserts that two byte arrays are equal.
assertArrayEquals(char[] expected, char[] actuals) : Asserts that two char arrays are equal.
assertNotNull(Object object) : Asserts that an object isn’t null.
For more such assert methods: https://junit.org/junit4/javadoc/4.13/org/junit/Assert.html
References
Wikipedia, tutorialspoint, javatpoint, junit.org