testing
Introduction
This blog is all about Unit Testing in Java. Unit testing basically means testing smaller components or units of your application like classes and methods.
Every developer, after writing their code in their main class, should test that service or controller via unit testing so that they can test their code to prove themselves.
After working on multiple frameworks for unit testing I personally found Junit the best framework for this task.
Simple Unit Testing Example
Suppose a class is there like given below with one method on the concatenation.
public class MyUnit {
public String concatenate(String one, String two){
return one + two;
}
}
Unit test for the above method can be written as:
public class MyUnitTest {
@Test
public void testConcatenate() {
MyUnit myUnit = new MyUnit();
String result = myUnit.concatenate("one", "two");
assertEquals("onetwo", result);
}
}
Notice how @Test is annotated which is done to signal to Unit Test Runner, which represents a unit test that should be executed.
Firstly, an instance of MyUnit class is created. Then it’s concatenate method is called with two String values.
Then the assertEquals method is called. This method actually does the unit testing. In this method, we compare the output of the method called concatenate() with the expected output.
If two values are equal nothing will happen but if values are not equal, an exception is thrown, and test method stops executing.
AssertEquals() method is statically imported from org.junit.Assert class.
You can have as many test cases as you want. The Test Runner will find and execute them all.
Database Unit Testing
If you need to test a DAO, you need to test all of the inserts, reads, updates and deletes work as expected.
Rather than testing individually for each operation(insert, read, update, delete) it is easier to test all CRUD operations inside the one test case.
Here is sample operation:
@Test
public void MyTest() throws Exception {
Connection connection = getConnection();
MyDao myDao = new MyDaoImpl(connection);
try{
myDao.insert("1", "one");
myDao.insert("2", "two");
assertEquals("one", myDao.read("1"));
assertEquals("two", myDao.read("2"));
myDao.update("1", "oneOne");
myDao.update("2", "twoTwo");
assertEquals("oneOne", myDao.read("1"));
assertEquals("twoTwo", myDao.read("2"));
myDao.delete("1");
myDao.delete("2");
assertNull(myDao.read("1"));
assertNull(myDao.read("2"));
} finally {
connection.rollback();
connection.close();
}
}
This test method first inserts data and then tests whether has been inserted or not.
Then it updates the value and then again it tests whether after the update, the output is true or not.
Finally, it deletes the data from the database and then again we check whether delete operation is successful or not.
If any operation fails, then it will throw an Exception.
Mockito
Mockito is a Java-based mocking framework, used in combination with other testing frameworks such as JUnit.
It internally uses the Java Reflection API and allows to create objects of service. A mock object returns dummy data and avoids external dependencies.
It simplifies the testing by creating dummy objects and creating dummy dependencies.
Basically Mockito creates a dummy object for a class that can be used for different purposes.
Mockito uses @mock annotation or mock() static method for creating mock objects.
Example :
public class CalcServiceTest {
CalculationService calculationService;
@Mock
AddService addService;
@BeforeEach
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCalc() {
calculationService = new CalculationService(addService);
int num1 = 20;
int num2 = 21;
int expected = 41;
when(addService.add(num1, num2)).thenReturn(expected);
int actual = calculationService.calc(num1, num2);
assertEquals(expected, actual);
}
}
Here, we are testing CalcService. @Mock is used to create a mock object of AddService class.
We need to call MockitoAnnotations.initMocks(this) to initialize objects annotated with @Mock.
Here when() and thenReturn() is used to add behavior to the mocked class. It means that when the mock object(addService) is called for add method with two parameters, then it returns the value of the function in the expected variable.
Finally, we check that the expected value which given by the function is equal to the actual value or not by using the assertEquals() method.
So Mockito basically allows the use of annotations to reduce the lines of test code to increase the readability of code.
JavaScript is a light-weight client-side scripting language, also the most widely used programming language in web and mobile applications, that our developers hold expertise in. We are a Java development company that enables enterprises to streamline operations and drive returns, using next-gen technologies, with our development services. Our development services include all your ERP needs from CRM, WFM, and HRM to eCommerce, accounting, and wealth management software. Get in touch with our experts to know more about how you can implement the latest technologies into your business.