Sun, May 15, 2022
Read in 2 minutes
In this article , we are going to see about writing unit tests .
Assume you are having a service to handle books.
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.
@Mock
Config config ;
// Next declare all the common variables
Private static final TEST_DATA = "dummydata" ;
//note - static variables should be in upper case
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 );
}
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()
Any(Book.class)
Any(HashMap.class)
Private String getFileContents(final String filename) throws Exception {
Return new String(Files.readAllBytes(Path.get("tst/"+filename);
}
Private byte[] getSampleData(String fileName) throws Exception {
String sampleString = getFileContents(fileName);
Return sampleString .getBytes();
}
ReflectionUtils has collection of reflection based utility method.One of the method is
setField(Class<?> targetClass,String name , Object value )
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 .