All about unit testcases and Mocking objects

Sun, May 15, 2022

Read in 2 minutes

Introduction :

In this article , we are going to see about writing unit tests .

Assume you are having a service to handle books.

BooksHandlingService.java


Public Book putBooksService(Book book , String bookID ) throws Exception;

Public Book  deleteBookService(String bookID) throws Exception;

Public Book getBookService(String bookID) throws Exception;

Public Book updateBookService(Book book , String bookID)

So,you need to write tests for the service.

BooksHandlingServiceTest.java

First mock all the required objects


@Mock
Config config ;
// Next declare all the common variables 
Private static final TEST_DATA = "dummydata" ;
//note - static variables should be in upper case

Initial Setups :

This @before will be executed before runnning all tests .

@before 
Setup() {
//create constructor for the service
BookService bookService = new BookService ();
}

Note - You can mock only methods which can return , if it is void you cannot mock and return anything.


@Test
Public void putBooksServiceTest() throws Exception {

//Create a dummy date to mock the method call
Book Bookobj = new Book();
Bookobj .set('someattribute');
//Mock the method 
When(bookService .getBookService(anyString).return(bookobj);
//Call the method
Book response = bookService .getBookService(Bookobj.getbookId);
Assert.assertNotNull(response );

}

Mockito Matchers :

If you want to match with any string , you can use

anyString

If you want to match with same equal string ,

Eq(String s )

If you want to match the String object ,

refEq()

To match with any class
Any(Book.class) 

Any(HashMap.class)

Try to get all the test data from a file


Private String getFileContents(final String filename) throws Exception {
Return new String(Files.readAllBytes(Path.get("tst/"+filename);
}

To get the sample data in Bytes for testing or mocking


Private byte[] getSampleData(String fileName) throws Exception {

String sampleString = getFileContents(fileName);
Return sampleString .getBytes();

}

RefelctionUtils in unit testing

ReflectionUtils has collection of reflection based utility method.One of the method is

setField(Class<?> targetClass,String name , Object value )
Example Scenario

you have the below class ,

public class Publish

@autowired
Product

While writing unit test for ‘Publish’ class ,

You have to mock Publish and Product type and using refelctionUtils , you need to set Field.

RefelctionUtils.SetField('Publish',"product",Product)

If you are not setting the Product using ReflectionUtils , you may get nullpointer exception .