1.

How can we mock void methods in Mockito?

Answer»

Consider we have a method called updateItem() which internally calls a void method called updateItem() which interacts with the database and updates the object.

public Item updateItem(Item item) { if (item == null || item.getItemId() < 0) { throw new IllegalArgumentException("Invalid Id"); } itemRepository.updateItem(item); //void method that updates database state return item;}

We can mock the void method in the following ways:

1. doNothing-when: This is used when we do not want to check for the return parameters and skip the actual execution. When this mocked method is called, then it does nothing. The test case would be:

@Testpublic void updateItemTest() { Item item = new Item(2, "Item 1"); doNothing().when(itemRepository).updateItem(any(Item.class)); itemService.updateItem(item);}

2. doAnswer-when: We can also make use of doAnswer-when whenever we need to perform additional actions like computing return values based on method parameters when a mocked method is called. This is done using the following:

@Testpublic void updateItemTest() { Item item = new Item(2, "Item 2"); doAnswer((args) -> { System.out.println("doAnswer block entered."); assertEquals(customer, args.getArgument(0)); return null; }).when(itemRepository).updateItem(any(Item.class)); itemService.updateItem(item);}

3. doThrow-when: If we want to throw an exception from void methods or any normal methods, then we can use doThrow-when as shown below:

@Test(expected = Exception.class)public void updateItemTest() { Item item = new Item(3, "Item 3"); doThrow(new Exception("Item Invalid")).when(itemRepository).updateItem(any(Item.class)); itemService.updateItem(item);}Conclusion

Writing Unit Test Cases has various ADVANTAGES like design testability, code testability, enhances code maintainability and helps developers enforce object-oriented principles that aids to avoid code smells like LONG methods, large conditions, long classes etc. It helps to identify any existing logic flaw in the application. Due to these reasons, it has become important for developers to know how to unit test the functionalities developed by them. JUNIT is one such popular framework that has robust support for unit TESTING.



Discussion

No Comment Found