{"id":1631,"date":"2015-08-21T09:33:23","date_gmt":"2015-08-21T13:33:23","guid":{"rendered":"http:\/\/springframework.guru\/?p=1631"},"modified":"2024-10-21T09:17:06","modified_gmt":"2024-10-21T13:17:06","slug":"mocking-unit-tests-mockito","status":"publish","type":"post","link":"https:\/\/springframework.guru\/mocking-unit-tests-mockito\/","title":{"rendered":"Mocking in Unit Tests with Mockito"},"content":{"rendered":"<p>Unit tests should be small tests (atomic), lightweight, and fast. However, an object under test might have dependencies on other objects. It might need to interact with a database, communicate with a mail server, or talk to a web service or a message queue. All these services might not be available during unit testing. Even if they are available, unit testing the <em>object under test<\/em> along with its dependencies can take unacceptable amount of time. What if?<\/p>\n<ul>\n<li><em>The web service is not reachable.<\/em><\/li>\n<li><em>The database is down for maintenance.<\/em><\/li>\n<li><em>The message queue is heavy and slow.<\/em><\/li>\n<\/ul>\n<p>These\u00a0all defeat the whole purpose of unit tests being atomic, lightweight, and fast. We want unit tests to execute in a few milliseconds. If the unit tests are slow, your builds become slow, which affects the productivity of your development team. The solution is to use mocking,\u00a0a way to provide test doubles for your classes being tested.<\/p>\n<p>If you&#8217;ve been following the <a href=\"http:\/\/springframework.guru\/solid-principles-object-oriented-programming\/\">SOLID Principles of Object Oriented Programming<\/a>, and using the Spring Framework for <a href=\"http:\/\/springframework.guru\/dependency-injection-example-using-spring\/\">Dependency Injection<\/a>, mocking becomes a natural solution for unit testing. You don&#8217;t really need a database connection. You just need an object that returns the expected result. If you&#8217;ve written tightly coupled code, you will have a difficult time using mocks. I&#8217;ve seen plenty of legacy code which could not be unit tested because it was so tightly coupled to other dependent objects. This untestable code did not follow the SOLID Principles of Object Oriented Programming, nor did it utilize Dependency Injection.<\/p>\n<h2>Mock Objects: Introduction<\/h2>\n<p>In unit test, a test double is a replacement of a dependent\u00a0component (collaborator) of the object under test. A test double provides the same interface as of the collaborator. It may not be the complete interface, but for the functionality required for the test. Also, the test double does not have to behave exactly as the collaborator. The purpose is to mimic the collaborator to make the object under test think that it is actually using the collaborator.<\/p>\n<p>Based on the role played during testing, there can be different types of test doubles, and mock object is one of them. Some other types are dummy object, fake object, and stub.<\/p>\n<p>What makes a mock object different from the others is that it uses behavior verification. It means that the mock object verifies that <em>it (the mock object) is being used correctly by the object under test<\/em>. If the verification succeeds, it can be considered that the object under test will correctly use the real collaborator.<\/p>\n<figure id=\"attachment_4223\" aria-describedby=\"caption-attachment-4223\" style=\"width: 560px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/bit.ly\/2yhpu6x\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4223 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02.png\" alt=\"Spring Framework 5\" width=\"560\" height=\"292\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02.png 560w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02-300x156.png 300w\" sizes=\"(max-width: 560px) 100vw, 560px\" \/><\/a><figcaption id=\"caption-attachment-4223\" class=\"wp-caption-text\">Click here to become a Spring Framework Guru with my online course Spring Framework 5: Beginner to Guru!<\/figcaption><\/figure>\n<h2>The Test Scenario<\/h2>\n<p>For the test scenario, consider a product ordering service. A client interacts with a DAO to fulfill a product ordering process.<\/p>\n<p>We will start with the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Product<\/code> domain object and the DAO interface, <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code>.<\/p>\n<h4>Product.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.unittest.mockito;\n\npublic class Product {\n\n}<\/pre>\n<h4>ProductDao.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.unittest.mockito;\n\npublic interface ProductDao {\n  int getAvailableProducts(Product product);\n  int orderProduct(Product product, int orderedQuantity);\n}<\/pre>\n<p>For the purpose of the example, I kept the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Product<\/code> class empty. But in real applications, it will typically be an entity with states having corresponding getter and setter methods, along with any implemented behaviors.<\/p>\n<p>In the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code> interface, we declared two methods:<\/p>\n<ul>\n<li>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">getAvailableProducts()<\/code> method returns the number of available quantity of a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Product<\/code> passed to it.<\/li>\n<li>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orderProduct()<\/code> places an order for a product.<\/li>\n<\/ul>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductService <\/code>class that we will write next is what we are interested on <strong>&#8211;<\/strong> <em>the object under test<\/em>.<\/p>\n<h4>ProductService.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.unittest.mockito;\n\npublic class ProductService {\n  private ProductDao productDao;\n  public void setProductDao(ProductDao productDao) {\n    this.productDao = productDao;\n  }\n  public boolean buy(Product product, int orderedQuantity) throws InsufficientProductsException {\n    boolean transactionStatus=false;\n    int availableQuantity = productDao.getAvailableProducts(product);\n    if (orderedQuantity &gt; availableQuantity) {\n      throw new InsufficientProductsException();\n    }\n    productDao.orderProduct(product, orderedQuantity);\n    transactionStatus=true;\n    return transactionStatus;\n  }\n\n}<\/pre>\n<p>The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductService<\/code> class above is composed of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code>, which is initialized through a setter method. In the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">buy()<\/code> method, we called <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">getAvailableProducts()<\/code> of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code> to check if sufficient quantity of the specified product is available. If not, an exception of type <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">InsufficientProductsException<\/code> is thrown. If sufficient quantity is available, we called the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orderProduct()<\/code> method of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code>.<\/p>\n<p>What we now need is to unit test <strong>ProductService<\/strong>. But as you can see, <strong>ProductService<\/strong> is composed of <strong>ProductDao<\/strong>, whose implementations we don\u2019t have yet. It can be a Spring Data JPA implementation retrieving data from a remote database, or an implementation that communicates with a Web service hosting a cloud-based repository \u2013 We don\u2019t know. Even if we have an implementation, we will use it later during integration testing, one of the <a title=\"Testing Software\" href=\"http:\/\/springframework.guru\/testing-software\/\" target=\"_blank\" rel=\"noopener noreferrer\">software testing <\/a>type I wrote earlier on. But now, we are <strong>not interested on any external implementations<\/strong> in this unit test.<\/p>\n<p>In unit tests, we should not to be bothered what the implementation is doing. What we want is to test that our <strong>ProductService<\/strong> is behaving as expected and that it is able to correctly use its collaborators. For that, we will mock <strong>ProductDao<\/strong> and <strong>Product<\/strong> using Mockito.<\/p>\n<p>The <strong>ProductService<\/strong> class also throws a custom exception, <strong>InsufficientProductsException<\/strong>. The code of the exception class is this.<\/p>\n<h4>InsufficientProductsException.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.unittest.mockito;\n\npublic class InsufficientProductsException extends Exception {\n  private static final long serialVersionUID = 1L;\n  private String message = null;\n  public InsufficientProductsException() { super(); }\n  public InsufficientProductsException(String message) {\n    super(message);\n    this.message = message;\n  }\n  public InsufficientProductsException(Throwable cause)\n  {\n    super(cause);\n  }\n  @Override\n  public String toString() {\n    return message;\n  }\n}<\/pre>\n<h2>Using Mockito<\/h2>\n<p>Mockito is a mocking framework for unit tests written in Java. It is an open source framework available at <a title=\"Mockito Source at Github\" href=\"https:\/\/github.com\/mockito\/mockito\" target=\"_blank\" rel=\"noopener noreferrer\">github<\/a>. You can use Mockito with JUnit to create and use mock objects during unit testing. To start using Mockito, <a title=\"Download Mockito\" href=\"https:\/\/code.google.com\/p\/mockito\/downloads\/list\" target=\"_blank\" rel=\"noopener noreferrer\">download<\/a> the JAR file and place it in your project class. If you are using Maven, you need to add its dependency in the pom.xml file, as shown below.<\/p>\n<h4>pom.xml<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"xml\" data-enlighter-theme=\"git\">&lt;project xmlns=\"http:\/\/maven.apache.org\/POM\/4.0.0\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\"\n  xsi:schemaLocation=\"http:\/\/maven.apache.org\/POM\/4.0.0 http:\/\/maven.apache.org\/maven-v4_0_0.xsd\"&gt;\n  &lt;modelVersion&gt;4.0.0&lt;\/modelVersion&gt;\n  &lt;groupId&gt;guru.springframework.unittest.quickstart&lt;\/groupId&gt;\n  &lt;artifactId&gt;unittest&lt;\/artifactId&gt;\n  &lt;packaging&gt;jar&lt;\/packaging&gt;\n  &lt;version&gt;1.0-SNAPSHOT&lt;\/version&gt;\n  &lt;name&gt;unittest&lt;\/name&gt;\n  &lt;url&gt;http:\/\/maven.apache.org&lt;\/url&gt;\n  &lt;dependencies&gt;\n    &lt;dependency&gt;\n     &lt;groupId&gt;junit&lt;\/groupId&gt;\n     &lt;artifactId&gt;junit&lt;\/artifactId&gt;\n     &lt;version&gt;4.12&lt;\/version&gt;\n     &lt;scope&gt;test&lt;\/scope&gt;\n    &lt;\/dependency&gt;\n      &lt;dependency&gt;\n          &lt;groupId&gt;org.hamcrest&lt;\/groupId&gt;\n          &lt;artifactId&gt;hamcrest-library&lt;\/artifactId&gt;\n          &lt;version&gt;1.3&lt;\/version&gt;\n          &lt;scope&gt;test&lt;\/scope&gt;\n      &lt;\/dependency&gt;\n      &lt;dependency&gt;\n          &lt;groupId&gt;org.mockito&lt;\/groupId&gt;\n          &lt;artifactId&gt;mockito-all&lt;\/artifactId&gt;\n          &lt;version&gt;1.9.5&lt;\/version&gt;\n      &lt;\/dependency&gt;\n  &lt;\/dependencies&gt;\n&lt;\/project&gt;<\/pre>\n<p>Once you have set up the required dependencies, you can start using Mockito. But, before we start any unit tests with mocks, let\u2019s have a quick overview of the key mocking concepts.<\/p>\n<h3>Mock Object Creation<\/h3>\n<p>For our example, it&#8217;s apparent that we need to mock <strong>ProductDao<\/strong> and <strong>Product<\/strong>. The simplest way is through calls to the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">mock()<\/code> method of the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">Mockito<\/code> class. The nice\u00a0thing about Mockito is that it allows creating mock objects of both interfaces and classes without forcing any explicit declarations.<\/p>\n<h4>MockCreationTest.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.unittest.mockito;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport static org.junit.Assert.*;\nimport static org.mockito.Mockito.*;\npublic class MockCreationTest {\n    private ProductDao productDao;\n    private Product product;\n    @Before\n    public void setupMock() {\n        product = mock(Product.class);\n        productDao = mock(ProductDao.class);\n    }\n    @Test\n    public void testMockCreation(){\n        assertNotNull(product);\n        assertNotNull(productDao);\n    }\n}<\/pre>\n<p>An alternative way is to use the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@Mock<\/code> annotation. When you use it, you will need to initialize the mocks with a call to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">MockitoAnnotations.initMocks(this)<\/code> or specify <strong>MockitoJUnitRunner<\/strong> as the JUnit test runner as <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">@RunWith(MockitoJUnitRunner.class)<\/code>.<\/p>\n<h4>MockCreationAnnotationTest.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.unittest.mockito;\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport static org.junit.Assert.*;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\npublic class MockCreationAnnotationTest {\n    @Mock\n    private ProductDao productDao;\n    @Mock\n    private Product product;\n    @Before\n    public void setupMock() {\n       MockitoAnnotations.initMocks(this);\n    }\n    @Test\n    public void testMockCreation(){\n        assertNotNull(product);\n        assertNotNull(productDao);\n    }\n}<\/pre>\n<h3>Stubbing<\/h3>\n<p>Stubbing means simulating the behavior of a mock object\u2019s method. We can stub a method on a mock object by setting up an expectation on the method invocation. For example, we can stub the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">getAvailableProducts()<\/code> method of the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code> mock to return a specific value when the method is called.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">. . .\n@Test\npublic void testBuy() throws InsufficientProductsException {\n    when(productDao.getAvailableProducts(product)).thenReturn(30);\n    assertEquals(30,productDao.getAvailableProducts(product));\n}\n. . .\n<\/pre>\n<p>In <strong>Line 4<\/strong> of the code above, we are stubbing <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">getAvailableProducts(product)<\/code> of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code> to return <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">30<\/code>. The <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">when()<\/code> method represents the trigger to start the stubbing and <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">thenReturn()<\/code> represents the action of the trigger \u2013 which in the example code is to return the value <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">30<\/code>. In <strong>Line 5<\/strong> with an <a title=\"JUnit Assetion\" href=\"http:\/\/springframework.guru\/unit-testing-junit-part-2\/\" target=\"_blank\" rel=\"noopener noreferrer\">assertion<\/a>, we confirmed that the stubbing performed as expected.<\/p>\n<h3>Verifying<\/h3>\n<p>Our objective is to test <strong>ProductService<\/strong>, and unitl\u00a0now we only mocked <strong>Product <\/strong>and <strong>ProductDao <\/strong>and stubbed <strong>getAvailableProducts()<\/strong> of <strong>ProductDao<\/strong>.<\/p>\n<p>We now want to verify the behavior of the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">buy()<\/code> method of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductService<\/code>. First, we want to verify whether it&#8217;s calling the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orderProduct()<\/code> of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code> with the required set of parameters.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">. . .\n@Test\npublic void testBuy() throws InsufficientProductsException {\n    when(productDao.getAvailableProducts(product)).thenReturn(30);\n    assertEquals(30,productDao.getAvailableProducts(product));\n    productService.buy(product, 5);\n    verify(productDao).orderProduct(product, 5);\n}\n. . .\n<\/pre>\n<p>In <strong>Line 6<\/strong> we called the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">buy()<\/code> method of <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductService<\/code> that is under test. In <strong>Line 7<\/strong>, we verified that the<code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\"> orderProduct()<\/code> method of the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code> mock get\u2019s invoked with the expected set of parameters (that we passed to <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">buy()<\/code>).<\/p>\n<p>Our test passed. But, not complete yet. We also want to verify:<\/p>\n<ul>\n<li><strong>Number of invocations done on a method<\/strong>: The <strong>buy()<\/strong> method invokes <strong>getAvailableProduct()<\/strong> at least once.<\/li>\n<li><strong>Sequence of Invocation<\/strong>: The <strong>buy()<\/strong> method first invokes <strong>getAvailableProduct()<\/strong>, and then <strong>orderProduct()<\/strong>.<\/li>\n<li><strong>Exception verification<\/strong>: The <strong>buy()<\/strong> method fails with <strong>InsufficientProductsException<\/strong> if order quantity passed to it is more than the available quantity returned by <strong>getAvailableProduct()<\/strong>.<\/li>\n<li><strong>Behavior during exception<\/strong>: The <strong>buy()<\/strong> method doesn\u2019t invokes <strong>orderProduct()<\/strong> when <strong>InsufficientProductsException<\/strong> is thrown.<\/li>\n<\/ul>\n<p>Here is the complete test code.<\/p>\n<h4>ProductServiceTest.java<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\">package guru.springframework.unittest.mockito;\n\n\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.mockito.InOrder;\nimport static org.mockito.Mockito.*;\nimport org.mockito.Mock;\n\npublic class ProductServiceTest {\n    private ProductService productService;\n    private ProductDao productDao;\n    private Product product;\n    private int purchaseQuantity = 15;\n\n    @Before\n    public void setupMock() {\n        productService = new ProductService();\n        product = mock(Product.class);\n        productDao = mock(ProductDao.class);\n        productService.setProductDao(productDao);\n    }\n\n    @Test\n    public void testBuy() throws InsufficientProductsException {\n        int availableQuantity = 30;\n        System.out.println(\"Stubbing getAvailableProducts(product) to return \" + availableQuantity);\n        when(productDao.getAvailableProducts(product)).thenReturn(availableQuantity);\n        System.out.println(\"Calling ProductService.buy(product,\" + purchaseQuantity + \")\");\n        productService.buy(product, purchaseQuantity);\n        System.out.println(\"Verifying ProductDao(product, \" + purchaseQuantity + \") is called\");\n        verify(productDao).orderProduct(product, purchaseQuantity);\n        System.out.println(\"Verifying getAvailableProducts(product) is called at least once\");\n        verify(productDao, atLeastOnce()).getAvailableProducts(product);\n        System.out.println(\"Verifying order of method calls on ProductDao: First call getAvailableProducts() followed by orderProduct()\");\n        InOrder order = inOrder(productDao);\n        order.verify(productDao).getAvailableProducts(product);\n        order.verify(productDao).orderProduct(product, purchaseQuantity);\n\n\n\n    }\n\n    @Test(expected = InsufficientProductsException.class)\n    public void purchaseWithInsufficientAvailableQuantity() throws InsufficientProductsException {\n        int availableQuantity = 3;\n        System.out.println(\"Stubbing getAvailableProducts(product) to return \" + availableQuantity);\n        when(productDao.getAvailableProducts(product)).thenReturn(availableQuantity);\n        try {\n            System.out.println(\"productService.buy(product\" + purchaseQuantity + \") should throw InsufficientProductsException\");\n            productService.buy(product, purchaseQuantity);\n        } catch (InsufficientProductsException e) {\n            System.out.println(\"InsufficientProductsException has been thrown\");\n            verify(productDao, times(0)).orderProduct(product, purchaseQuantity);\n            System.out.println(\"Verified orderProduct(product, \" + purchaseQuantity + \") is not called\");\n            throw e;\n        }\n    }\n\n}\n<\/pre>\n<p>I have already explained the initial code of the test class above. So we will start with <strong>Line 36 \u2013 Line 38<\/strong> where we used the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">inOrder()<\/code> method to verify the order of method invocation that the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">buy()<\/code> method makes on <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">ProductDao<\/code>.<\/p>\n<p>Then we wrote a <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">purchaseWithInsufficientAvailableQuantity()<\/code> test method to check whether an <strong>InsufficientProductsException<\/strong> gets thrown, as expected, when an order with quantity more than the available quantity is made. We also verified in <strong>Line 54<\/strong> that if <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">InsufficientProductsException<\/code> gets thrown, the <code class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">orderProduct()<\/code> method is not invoked.<\/p>\n<p>The output of the test is this.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"java\" data-enlighter-theme=\"git\" data-enlighter-linenumbers=\"false\">-------------------------------------------------------\nT E S T S\n-------------------------------------------------------\n\nRunning guru.springframework.unittest.mockito.ProductServiceTest\nStubbing getAvailableProducts(product) to return 30\nCalling ProductService.buy(product,15)\nVerifying ProductDao(product, 15) is called\nVerifying getAvailableProducts(product) is called at least once\nVerifying order of method calls on ProductDao: First call getAvailableProducts() followed by orderProduct()\nStubbing getAvailableProducts(product) to return 3\nproductService.buy(product15) should throw InsufficientProductsException\nInsufficientProductsException has been thrown\nVerified orderProduct(product, 15) is not called\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.077 sec<\/pre>\n<h2>Mockito Mocks vs Mockito Spies<\/h2>\n<p>In testing Spring Boot applications sometimes you need to access the real component. This is where Mockito Spies come into the picture. If you&#8217;d like to learn more about using Mockito Spies, <a href=\"http:\/\/springframework.guru\/mockito-mock-vs-spy-in-spring-boot-tests\/\">check out this post<\/a>.<\/p>\n<h2>Summary<\/h2>\n<p>Mocking in unit testing is extensively used in <a href=\"http:\/\/springframework.guru\/using-the-spring-framework-for-enterprise-application-development\/\" target=\"_blank\" rel=\"noopener noreferrer\">Enterprise Application Development with Spring<\/a>. By using Mockito, you can replace the <strong>@Autowired<\/strong> components in the class you want to test with mock objects. You will be unit testing controllers by injecting mock services. You will also be setting up services to use mock DAOs to unit test the service layer. To unit test the DAO layer, you will mock the database APIs. The list is endless\u00a0\u2013 It depends on the type of application you are working on and the object under test.\u00a0If you&#8217;re following the <a href=\"http:\/\/springframework.guru\/dependency-inversion-principle\/\" target=\"_blank\" rel=\"noopener noreferrer\">Dependency Inversion Principle<\/a> and using <a href=\"http:\/\/springframework.guru\/dependency-injection-example-using-spring\/\" target=\"_blank\" rel=\"noopener noreferrer\">Dependency\u00a0Injection<\/a>, mocking becomes easy.<\/p>\n<p>The Mockito library is a very large and mature mocking library. It is very popular to use for mocking objects in unit tests. Mockito is popular because it is easy to use, and very versatile. I wrote this post as just an introduction to mocking and Mockito. Checkout <a href=\"https:\/\/javadoc.io\/doc\/org.mockito\/mockito-core\/latest\/org\/mockito\/Mockito.html\" target=\"_blank\" rel=\"noopener noreferrer\">the official Mockito documentation<\/a> to learn about all the capabilities of Mockito.<\/p>\n<figure id=\"attachment_4223\" aria-describedby=\"caption-attachment-4223\" style=\"width: 560px\" class=\"wp-caption aligncenter\"><a href=\"http:\/\/bit.ly\/2yhpu6x\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-4223 size-full\" src=\"http:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02.png\" alt=\"Spring Framework 5\" width=\"560\" height=\"292\" srcset=\"https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02.png 560w, https:\/\/springframework.guru\/wp-content\/uploads\/2018\/06\/ReactiveIsComing2NewSmall02-300x156.png 300w\" sizes=\"(max-width: 560px) 100vw, 560px\" \/><\/a><figcaption id=\"caption-attachment-4223\" class=\"wp-caption-text\">Become a Spring Framework Guru with my Spring Framework 5: Beginner to Guru online course!<\/figcaption><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Unit tests should be small tests (atomic), lightweight, and fast. However, an object under test might have dependencies on other objects. It might need to interact with a database, communicate with a mail server, or talk to a web service or a message queue. All these services might not be available during unit testing. Even [&hellip;]<a href=\"https:\/\/springframework.guru\/mocking-unit-tests-mockito\/\" class=\"df-link-excerpt\">Continue reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":4584,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_lmt_disableupdate":"","_lmt_disable":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"Mocking in Unit Tests with Mockito #java #mockito","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":{"image_generator_settings":{"template":"highway","enabled":false},"version":2}},"categories":[20,33,85],"tags":[95,131],"class_list":["post-1631","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","category-junit","category-testing","tag-mockito","tag-unit-testing"],"jetpack_publicize_connections":[],"aioseo_notices":[],"modified_by":"jt","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/springframework.guru\/wp-content\/uploads\/2015\/03\/Banner560x292_01web.jpg","jetpack_shortlink":"https:\/\/wp.me\/p5BZrZ-qj","_links":{"self":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/1631"}],"collection":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/comments?post=1631"}],"version-history":[{"count":9,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/1631\/revisions"}],"predecessor-version":[{"id":8267,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/posts\/1631\/revisions\/8267"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media\/4584"}],"wp:attachment":[{"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/media?parent=1631"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/categories?post=1631"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/springframework.guru\/wp-json\/wp\/v2\/tags?post=1631"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}