Mockito

Mockito is an open source testing framework for Java-based applications that are released under the MIT License. It allows the developers to create mock objects for TDD, which is isolated from the framework. It uses the Java Reflection API to create mock objects, and has simple APIs to write test cases. It also facilitates the developers to have a check on the order in which the methods are invoked.

Mockito has a static mock() method, which can be used to create mock objects. It also facilitates the creation of mock objects using the @Mock annotation. methodMockitoAnnotations.initMocks(this) instructs to initialize all the annotated fields that are annotated by @Mock. If we forget to do so, the objects will be null. @RunWith(MokitoJUnitRunner.class) also does the same. MockitoJUnitRunner is the custom runner that is used by JUnit.

Mockito works on the principle of returning predefined values. To test the function with the mock object, we invoke the when() function as, Mockito, when(), and pass it the method under testing as an argument. Mock objects are fake objects, which means the methods are also fake. So, depending on the return type of the method, we will define the set of values as an argument of Mokito, using the method thenXXX(). Oops! It's complicated. No, actually, it's very easy, just wait for a while, and I am sure you will agree with me. But before discussing further, let's first find out what type of values will be returned by the thenXXX() method. The following are the methods that are used to specify what values are to be returned:

  • thenReturn: This is used to return a specified value
  • thenThrow: This throws a specified exception
  • then: This returns an answer by the user-defined code
  • thenAnswer: This is the same as then
  • thenCallRealMethod: This gives a call to the real method

Mock testing is a simple three-step process, which can be listed as follows:

  1. Initialization of the dependencies by the mock object for the class under test.
  2. Executing the operation to test.
  3. Writing test conditions to check whether the operation gives expected results or not.

Let's use Mockito to create a mock object of BookDAO, and use it step by step in testing, as follows:

  1. Download mokito-all-1.9.5.jar, and add it to the Ch07_JdbeTemplate_Testing project that we are using as our base project.
  2. Create Spring_Mokito_TestBookDAO_JdbcTemplate as the JUnit test case in the com.packt.ch07.unit_tests package.
  3. Add a data member of type BookDAO, and annotate it with the @Mock annotation.
  4. To initialize the mock object, invoke the initiMoks() method of Mockito in the setup() method, as shown in the following piece of code:
        public classSpring_Mokito_TestBookDAO_JdbcTemplate { 
@Mock
BookDAO bookDAO_JdbcTemplate;

@Before
public void setUp()throws Exception
{
MockitoAnnotations.initMocks(this);
}
}
  1. Let's now add code to test addBook(), where we will first define the values that we expect the function under the test to return as. Then, we will use the assertXXX() methods to test the behavior, as shown in the following piece of code:
        @Test 
public void testAddBook() {
Book book = new Book("Book_Test", 909090L, "Test
Publication", 1000, "Test Book description",
"Test author");
//set the behavior for values to return in our case
//addBook() method
Mockito.when(bookDAO_JdbcTemplate.addBook(book)).thenReturn(1);
// invoke the function under test
int rows_insert = bookDAO_JdbcTemplate.addBook(book);
// assert the actual value return by the method under test
//to the expected behaivour by mock object
assertEquals(1, rows_insert);
}

Observe the value of the method thenReturn(). We used 1, as the method is expected to return the number of rows which have been added. In the same way, according to the return type of the method under test, the developers need to return some constant values. Whenever the method under testing is invoked, the specified value or set of values will be returned.

  1. Execute the test case, and test the behavior. We will get all the test cases executed successfully.
  2. Let's add the code for other findAllBooks (String) and the deleteBook() methods as well:
        @Test 
public void testDeleteBook() {
//with ISBN which does exit in the table Book
long ISBN = 909090L;
Mockito.when(bookDAO_JdbcTemplate.deleteBook(ISBN)).
then Return(true);

boolean deleted = bookDAO_JdbcTemplate.deleteBook(ISBN);
assertTrue(deleted);
}

@Test
public void testFindAllBooks_Author() {
List<Book>books=newArrayList();
books.add(new Book("Book_Test", 909090L, "Test
Publication", 1000, "Test Book description", "Test
author") );

Mockito.when(bookDAO_JdbcTemplate.findAllBooks("Test
author")).thenReturn(books);
assertTrue(books.size()>0);
assertEquals(1, books.size());
assertEquals("Book_Test",books.get(0).getBookName());
}

In the previous demo, we discussed unit testing of the DAO layer in both a real-time environment as well as using mock objects. Now, let's test the controller using the Spring MVC test framework in the following sections.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.36.141