├── .gitignore ├── LICENSE ├── Mockito-Exact-Source-After-Video.zip ├── MockitoTutorialForBeginners.pdf ├── README.md ├── Step01.md ├── Step02.md ├── Step03.md ├── Step04.md ├── Step05.md ├── Step06.md ├── Step07.md ├── Step08.md ├── Step09.md ├── Step10.md ├── Step11.md ├── Step12.md ├── Step13.md ├── Step14.md ├── Step15.md ├── Step16.md ├── Step17.md ├── Step18.md ├── StepReference.md ├── mockito-real-world-example-with-spring.zip ├── pom.xml └── src ├── main └── java │ └── com │ └── in28minutes │ ├── business │ └── TodoBusinessImpl.java │ ├── data │ └── api │ │ └── TodoService.java │ ├── junit │ ├── business │ │ ├── ClientBO.java │ │ ├── ClientBOImpl.java │ │ └── exception │ │ │ └── DifferentCurrenciesException.java │ ├── helper │ │ └── StringHelper.java │ └── model │ │ ├── Amount.java │ │ ├── AmountImpl.java │ │ ├── Client.java │ │ ├── ClientImpl.java │ │ ├── ClientType.java │ │ ├── Collateral.java │ │ ├── CollateralImpl.java │ │ ├── CollateralType.java │ │ ├── Currency.java │ │ ├── Product.java │ │ ├── ProductImpl.java │ │ └── ProductType.java │ └── powermock │ ├── SystemUnderTest.java │ └── UtilityClass.java └── test └── java └── com ├── clarity └── business │ ├── ClientBOTest.java │ └── ClientBOTestRefactored.java └── in28minutes ├── business ├── TodoBusinessImplMockitoInjectMocksTest.java ├── TodoBusinessImplMockitoRulesTest.java ├── TodoBusinessImplMockitoTest.java └── TodoBusinessImplStubTest.java ├── data └── stub │ └── TodoServiceStub.java ├── junit ├── helper │ ├── ArraysCompareTest.java │ ├── ArraysTest.java │ ├── QuickBeforeAfterTest.java │ ├── StringHelperParameterizedTest.java │ └── StringHelperTest.java └── suite │ └── DummyTestSuite.java ├── mockito ├── FirstMockitoTest.java ├── HamcrestMatcherTest.java ├── ListTest.java └── SpyTest.java └── powermock ├── PowerMockitoMockingConstructorTest.java ├── PowerMockitoMockingStaticMethodTest.java └── PowerMockitoTestingPrivateMethodTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # BlueJ files 8 | *.ctxt 9 | 10 | # Mobile Tools for Java (J2ME) 11 | .mtj.tmp/ 12 | 13 | # Package Files # 14 | *.jar 15 | *.war 16 | *.ear 17 | *.zip 18 | *.tar.gz 19 | *.rar 20 | *.cmd 21 | *.classpath 22 | *.settings 23 | *.project 24 | *.mvn 25 | mvnw 26 | target 27 | *.DS_Store 28 | 29 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 30 | hs_err_pid* 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /Mockito-Exact-Source-After-Video.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/in28minutes/MockitoTutorialForBeginners/04ad1f28cfc7f672b1d697249dfaa074b2efdd88/Mockito-Exact-Source-After-Video.zip -------------------------------------------------------------------------------- /MockitoTutorialForBeginners.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/in28minutes/MockitoTutorialForBeginners/04ad1f28cfc7f672b1d697249dfaa074b2efdd88/MockitoTutorialForBeginners.pdf -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mockito Tutorial For Beginners 2 | 3 | [![Image](https://www.springboottutorial.com/images/Course-Learn-Unit-Testing-With-JUnit-and-Mockito.png "Mockito Tutorial : Learn mocking with 25 Junit Examples")](https://www.udemy.com/course/mockito-tutorial-with-junit-examples/) 4 | 5 | ## Gain expertise on the most popular java mocking framework 6 | 7 | * [Installing Eclipse, Maven and Java](#installing-tools) 8 | * [Running Examples](#running-examples) 9 | * [Course Overview](#course-overview) 10 | - [Course Steps](#step-list) 11 | - [Expectations](#expectations) 12 | * [About in28Minutes](#about-in28minutes) 13 | - [Our Beliefs](#our-beliefs) 14 | - [Our Approach](#our-approach) 15 | - [Find Us](#useful-links) 16 | - [Other Courses](#other-courses) 17 | 18 | ## Installing Tools 19 | - PDF : https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf 20 | - Video : https://www.youtube.com/watch?v=eqRF4xHoGck 21 | 22 | ## Course Overview 23 | ### Step List 24 | 25 | #### JUnit 26 | - Step 01 : Need for Unit Testing 27 | - Step 02 : Setting up your First JUnit 28 | - Step 03 : First Successful JUnit. Green Bar and assertEquals 29 | - Step 04 : Refactoring Your First JUnit Test 30 | - Step 05 : Second JUnit Example assertTrue and assertFalse 31 | - Step 06 : @Before @After 32 | - Step 07 : @BeforeClass @AfterClass 33 | - Step 08 : Comparing Arrays in JUnit Tests 34 | - Step 09 : Testing Exceptions in JUnit Tests 35 | - Step 10 : Testing Performance in JUnit Tests 36 | - Step 11 : Parameterized Tests 37 | - Step 12 : Organize JUnits into Suites 38 | 39 | #### Mockito 40 | - Step 01 : Set up an Eclipse Project with JUnit and Mockito frameworks. First Green Bar. 41 | - Step 02 : Example to start understanding why we need mocks. 42 | - Step 03 : What is a stub? Create an unit test using Stub? Disadvantages of Stubs. 43 | - Step 04 : Your first Mockito code! Hurrah!!! Lets use Mockito to mock TodoService. 44 | - Step 05 : Stubbing variations with Mockito. A few mockito examples mocking List class : Multiple return values, Argument Matchers and throwing exceptions. 45 | - Some Theory : Mockito vs EasyMock [https://github.com/mockito/mockito/wiki/Mockito-vs-EasyMock](https://github.com/mockito/mockito/wiki/Mockito-vs-EasyMock) 46 | - Step 06 : Introduction to BDD. Given When Then. BDD Mockito Syntax. 47 | - Step 07 : How to verify calls on a mock? Verify how many times a method is called. We will add deleteTodo method to the TodoService. 48 | - Step 08 : How to capture an argument which is passed to a mock? 49 | - Step 09 : Hamcrest Matchers. 50 | - Step 10 : Let's simplify things with Mockito Annotations. @Mock, @InjectMocks, @RunWith(MockitoJUnitRunner.class), @Captor 51 | - Step 11 : JUnit Rules. Using MockitoJUnit.rule() instead of @RunWith(MockitoJUnitRunner.class). 52 | - Step 12 : Real world Example with Spring 53 | - Step 13 : What is a spy? How to spy with Mockito? 54 | - Step 14 : Some Theory : Why does Mockito not allow stubbing final and private methods? 55 | - Step 15 : Using PowerMock and Mockito to mock a Static Method. 56 | - Step 16 : Using PowerMock and Mockito to invoke a private Method. 57 | - Step 17 : Using PowerMock and Mockito to mock a constructor. 58 | - Step 18 : Good Unit Tests. 59 | 60 | ### Expectations 61 | - You should know Java. 62 | - You are NOT expected to have any experience with Eclipse or Maven. 63 | - We will help you install Eclipse and get up and running with Maven. 64 | 65 | ### Running Examples 66 | - Download the zip or clone the Git repository. 67 | - Unzip the zip file (if you downloaded one) 68 | - Open Command Prompt and Change directory (cd) to folder containing pom.xml 69 | - Open Eclipse 70 | - File -> Import -> Existing Maven Project -> Navigate to the folder where you unzipped the zip 71 | - Select the right project 72 | - Choose the Spring Boot Application file (search for @SpringBootApplication) 73 | - Right Click on the file and Run as Java Application 74 | - You are all Set 75 | 76 | ### Troubleshooting 77 | - Refer our TroubleShooting Guide - https://github.com/in28minutes/in28minutes-initiatives/tree/master/The-in28Minutes-TroubleshootingGuide-And-FAQ 78 | 79 | ## Youtube Playlists - 500+ Videos 80 | 81 | [Click here - 30+ Playlists with 500+ Videos on Spring, Spring Boot, REST, Microservices and the Cloud](https://www.youtube.com/user/rithustutorials/playlists?view=1&sort=lad&flow=list) 82 | 83 | ## Keep Learning in28Minutes 84 | 85 | in28Minutes is creating amazing solutions for you to learn Spring Boot, Full Stack and the Cloud - Docker, Kubernetes, AWS, React, Angular etc. - [Check out all our courses here](https://github.com/in28minutes/learn) 86 | -------------------------------------------------------------------------------- /Step01.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Set up an Eclipse Project. 3 | - Set up JUnit and Mockito frameworks. 4 | - First Green Bar 5 | 6 | ## Useful Snippets 7 | - You should know JUnit. You can find our free JUnit Course here - [JUnit](https://www.udemy.com/course/junit-tutorial-for-beginners-with-java-examples/) 8 | - Dependencies for JUnit and Mockito are listed below 9 | 10 | ``` 11 | 12 | 13 | junit 14 | junit 15 | 4.12 16 | test 17 | 18 | 19 | org.mockito 20 | mockito-all 21 | 1.10.19 22 | test 23 | 24 | 25 | ``` 26 | ## Files List 27 | ### /pom.xml 28 | ``` 29 | 31 | 4.0.0 32 | com.in28minutes.mockito 33 | mockito-tutorial 34 | 0.0.1-SNAPSHOT 35 | 36 | 37 | junit 38 | junit 39 | 4.12 40 | test 41 | 42 | 43 | org.mockito 44 | mockito-all 45 | 1.10.19 46 | test 47 | 48 | 49 | 50 | ``` 51 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 52 | ``` 53 | package com.in28minutes.mockito; 54 | 55 | import static org.junit.Assert.assertTrue; 56 | 57 | import org.junit.Test; 58 | 59 | public class FirstMockitoTest { 60 | 61 | @Test 62 | public void test() { 63 | assertTrue(true); 64 | } 65 | 66 | } 67 | ``` 68 | -------------------------------------------------------------------------------- /Step02.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Start Creating an example to start understanding why we need mocks. 3 | - We want to interact with a Todo Management application. 4 | - We want to provide a filtering around Spring related Todo's 5 | 6 | ## Files List 7 | ### /pom.xml 8 | ``` 9 | 11 | 4.0.0 12 | com.in28minutes.mockito 13 | mockito-tutorial 14 | 0.0.1-SNAPSHOT 15 | 16 | 17 | junit 18 | junit 19 | 4.12 20 | test 21 | 22 | 23 | org.mockito 24 | mockito-all 25 | 1.10.19 26 | test 27 | 28 | 29 | 30 | ``` 31 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 32 | ``` 33 | package com.in28minutes.business; 34 | 35 | import java.util.ArrayList; 36 | import java.util.List; 37 | 38 | import com.in28minutes.data.api.TodoService; 39 | 40 | public class TodoBusinessImpl { 41 | private TodoService todoService; 42 | 43 | TodoBusinessImpl(TodoService todoService) { 44 | this.todoService = todoService; 45 | } 46 | 47 | public List retrieveTodosRelatedToSpring(String user) { 48 | List filteredTodos = new ArrayList(); 49 | List allTodos = todoService.retrieveTodos(user); 50 | for (String todo : allTodos) { 51 | if (todo.contains("Spring")) { 52 | filteredTodos.add(todo); 53 | } 54 | } 55 | return filteredTodos; 56 | } 57 | } 58 | ``` 59 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 60 | ``` 61 | package com.in28minutes.data.api; 62 | 63 | import java.util.List; 64 | 65 | // External Service - Lets say this comes from WunderList 66 | public interface TodoService { 67 | public List retrieveTodos(String user); 68 | } 69 | ``` 70 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 71 | ``` 72 | package com.in28minutes.mockito; 73 | 74 | import static org.junit.Assert.assertTrue; 75 | 76 | import org.junit.Test; 77 | 78 | public class FirstMockitoTest { 79 | 80 | @Test 81 | public void test() { 82 | assertTrue(true); 83 | } 84 | 85 | } 86 | ``` 87 | -------------------------------------------------------------------------------- /Step03.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - What is a stub? 3 | - Create an unit test using Stub? 4 | - Disadvantages of Stubs 5 | 6 | ## Exercise 7 | - Improve the asserts for the ArrayList in the test TodoBusinessImplStubTest. 8 | 9 | ## Files List 10 | ### /pom.xml 11 | ``` 12 | 14 | 4.0.0 15 | com.in28minutes.mockito 16 | mockito-tutorial 17 | 0.0.1-SNAPSHOT 18 | 19 | 20 | junit 21 | junit 22 | 4.12 23 | test 24 | 25 | 26 | org.mockito 27 | mockito-all 28 | 1.10.19 29 | test 30 | 31 | 32 | 33 | ``` 34 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 35 | ``` 36 | package com.in28minutes.business; 37 | 38 | import java.util.ArrayList; 39 | import java.util.List; 40 | 41 | import com.in28minutes.data.api.TodoService; 42 | 43 | public class TodoBusinessImpl { 44 | private TodoService todoService; 45 | 46 | TodoBusinessImpl(TodoService todoService) { 47 | this.todoService = todoService; 48 | } 49 | 50 | public List retrieveTodosRelatedToSpring(String user) { 51 | List filteredTodos = new ArrayList(); 52 | List allTodos = todoService.retrieveTodos(user); 53 | for (String todo : allTodos) { 54 | if (todo.contains("Spring")) { 55 | filteredTodos.add(todo); 56 | } 57 | } 58 | return filteredTodos; 59 | } 60 | } 61 | ``` 62 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 63 | ``` 64 | package com.in28minutes.data.api; 65 | 66 | import java.util.List; 67 | 68 | // External Service - Lets say this comes from WunderList 69 | public interface TodoService { 70 | public List retrieveTodos(String user); 71 | } 72 | ``` 73 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 74 | ``` 75 | package com.in28minutes.business; 76 | 77 | import static org.junit.Assert.assertEquals; 78 | 79 | import java.util.List; 80 | 81 | import org.junit.Test; 82 | 83 | import com.in28minutes.data.api.TodoService; 84 | import com.in28minutes.data.stub.TodoServiceStub; 85 | 86 | public class TodoBusinessImplStubTest { 87 | 88 | @Test 89 | public void usingAStub() { 90 | TodoService todoService = new TodoServiceStub(); 91 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 92 | List todos = todoBusinessImpl 93 | .retrieveTodosRelatedToSpring("Ranga"); 94 | assertEquals(2, todos.size()); 95 | } 96 | } 97 | ``` 98 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 99 | ``` 100 | package com.in28minutes.data.stub; 101 | 102 | import java.util.Arrays; 103 | import java.util.List; 104 | 105 | import com.in28minutes.data.api.TodoService; 106 | 107 | public class TodoServiceStub implements TodoService { 108 | public List retrieveTodos(String user) { 109 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 110 | "Learn to Dance"); 111 | } 112 | } 113 | ``` 114 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 115 | ``` 116 | package com.in28minutes.mockito; 117 | 118 | import static org.junit.Assert.assertTrue; 119 | 120 | import org.junit.Test; 121 | 122 | public class FirstMockitoTest { 123 | 124 | @Test 125 | public void test() { 126 | assertTrue(true); 127 | } 128 | 129 | } 130 | ``` 131 | -------------------------------------------------------------------------------- /Step04.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Your first Mockito code! Hurrah!!! 3 | - Lets use Mockito to mock TodoService 4 | 5 | ## Useful Snippets and References 6 | Easier Static Imports 7 | ``` 8 | Window > Preferences > Java > Editor > Content Assist > Favorites 9 | org.junit.Assert 10 | org.mockito.BDDMockito 11 | org.mockito.Mockito 12 | org.hamcrest.Matchers 13 | org.hamcrest.CoreMatchers 14 | ``` 15 | ## Exercises 16 | - Play around with code 17 | - Think what JUnit best practises we are NOT adhering to 18 | - Visit Mockito Official Documentation - [Mockito Documentation] (http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html) 19 | 20 | ## Files List 21 | ### /pom.xml 22 | ``` 23 | 25 | 4.0.0 26 | com.in28minutes.mockito 27 | mockito-tutorial 28 | 0.0.1-SNAPSHOT 29 | 30 | 31 | junit 32 | junit 33 | 4.12 34 | test 35 | 36 | 37 | org.mockito 38 | mockito-all 39 | 1.10.19 40 | test 41 | 42 | 43 | 44 | ``` 45 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 46 | ``` 47 | package com.in28minutes.business; 48 | 49 | import java.util.ArrayList; 50 | import java.util.List; 51 | 52 | import com.in28minutes.data.api.TodoService; 53 | 54 | public class TodoBusinessImpl { 55 | private TodoService todoService; 56 | 57 | TodoBusinessImpl(TodoService todoService) { 58 | this.todoService = todoService; 59 | } 60 | 61 | public List retrieveTodosRelatedToSpring(String user) { 62 | List filteredTodos = new ArrayList(); 63 | List allTodos = todoService.retrieveTodos(user); 64 | for (String todo : allTodos) { 65 | if (todo.contains("Spring")) { 66 | filteredTodos.add(todo); 67 | } 68 | } 69 | return filteredTodos; 70 | } 71 | } 72 | ``` 73 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 74 | ``` 75 | package com.in28minutes.data.api; 76 | 77 | import java.util.List; 78 | 79 | // External Service - Lets say this comes from WunderList 80 | public interface TodoService { 81 | public List retrieveTodos(String user); 82 | } 83 | ``` 84 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 85 | ``` 86 | package com.in28minutes.business; 87 | 88 | import static org.junit.Assert.assertEquals; 89 | import static org.mockito.Mockito.mock; 90 | import static org.mockito.Mockito.when; 91 | 92 | import java.util.Arrays; 93 | import java.util.List; 94 | 95 | import org.junit.Test; 96 | 97 | import com.in28minutes.data.api.TodoService; 98 | 99 | public class TodoBusinessImplMockitoTest { 100 | 101 | @Test 102 | public void usingMockito() { 103 | TodoService todoService = mock(TodoService.class); 104 | List allTodos = Arrays.asList("Learn Spring MVC", 105 | "Learn Spring", "Learn to Dance"); 106 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 107 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 108 | List todos = todoBusinessImpl 109 | .retrieveTodosRelatedToSpring("Ranga"); 110 | assertEquals(2, todos.size()); 111 | } 112 | } 113 | ``` 114 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 115 | ``` 116 | package com.in28minutes.business; 117 | 118 | import static org.junit.Assert.assertEquals; 119 | 120 | import java.util.List; 121 | 122 | import org.junit.Test; 123 | 124 | import com.in28minutes.data.api.TodoService; 125 | import com.in28minutes.data.stub.TodoServiceStub; 126 | 127 | public class TodoBusinessImplStubTest { 128 | 129 | @Test 130 | public void usingAStub() { 131 | TodoService todoService = new TodoServiceStub(); 132 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 133 | List todos = todoBusinessImpl 134 | .retrieveTodosRelatedToSpring("Ranga"); 135 | assertEquals(2, todos.size()); 136 | } 137 | } 138 | ``` 139 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 140 | ``` 141 | package com.in28minutes.data.stub; 142 | 143 | import java.util.Arrays; 144 | import java.util.List; 145 | 146 | import com.in28minutes.data.api.TodoService; 147 | 148 | public class TodoServiceStub implements TodoService { 149 | public List retrieveTodos(String user) { 150 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 151 | "Learn to Dance"); 152 | } 153 | } 154 | ``` 155 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 156 | ``` 157 | package com.in28minutes.mockito; 158 | 159 | import static org.junit.Assert.assertTrue; 160 | 161 | import org.junit.Test; 162 | 163 | public class FirstMockitoTest { 164 | 165 | @Test 166 | public void test() { 167 | assertTrue(true); 168 | } 169 | 170 | } 171 | ``` 172 | -------------------------------------------------------------------------------- /Step05.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - A few mockito examples mocking List class 3 | - Multiple return values 4 | - Introduction to Argument Matchers 5 | - stub method 6 | - Throwing exceptions 7 | 8 | ## Exercises 9 | - What if we combine a matcher with hardcoded value when stubbing. 10 | - Mock a few other List Methods. 11 | - What happens if an unstubbed method is called? 12 | - By default, for all methods that return a value, a mock will return either null, a a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean. 13 | 14 | ## Files List 15 | ### /pom.xml 16 | ``` 17 | 19 | 4.0.0 20 | com.in28minutes.mockito 21 | mockito-tutorial 22 | 0.0.1-SNAPSHOT 23 | 24 | 25 | junit 26 | junit 27 | 4.12 28 | test 29 | 30 | 31 | org.mockito 32 | mockito-all 33 | 1.10.19 34 | test 35 | 36 | 37 | 38 | ``` 39 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 40 | ``` 41 | package com.in28minutes.business; 42 | 43 | import java.util.ArrayList; 44 | import java.util.List; 45 | 46 | import com.in28minutes.data.api.TodoService; 47 | 48 | public class TodoBusinessImpl { 49 | private TodoService todoService; 50 | 51 | TodoBusinessImpl(TodoService todoService) { 52 | this.todoService = todoService; 53 | } 54 | 55 | public List retrieveTodosRelatedToSpring(String user) { 56 | List filteredTodos = new ArrayList(); 57 | List allTodos = todoService.retrieveTodos(user); 58 | for (String todo : allTodos) { 59 | if (todo.contains("Spring")) { 60 | filteredTodos.add(todo); 61 | } 62 | } 63 | return filteredTodos; 64 | } 65 | } 66 | ``` 67 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 68 | ``` 69 | package com.in28minutes.data.api; 70 | 71 | import java.util.List; 72 | 73 | // External Service - Lets say this comes from WunderList 74 | public interface TodoService { 75 | public List retrieveTodos(String user); 76 | } 77 | ``` 78 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 79 | ``` 80 | package com.in28minutes.business; 81 | 82 | import static org.junit.Assert.assertEquals; 83 | import static org.mockito.Mockito.mock; 84 | import static org.mockito.Mockito.when; 85 | 86 | import java.util.Arrays; 87 | import java.util.List; 88 | 89 | import org.junit.Test; 90 | 91 | import com.in28minutes.data.api.TodoService; 92 | 93 | public class TodoBusinessImplMockitoTest { 94 | 95 | @Test 96 | public void usingMockito() { 97 | TodoService todoService = mock(TodoService.class); 98 | List allTodos = Arrays.asList("Learn Spring MVC", 99 | "Learn Spring", "Learn to Dance"); 100 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 101 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 102 | List todos = todoBusinessImpl 103 | .retrieveTodosRelatedToSpring("Ranga"); 104 | assertEquals(2, todos.size()); 105 | } 106 | } 107 | ``` 108 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 109 | ``` 110 | package com.in28minutes.business; 111 | 112 | import static org.junit.Assert.assertEquals; 113 | 114 | import java.util.List; 115 | 116 | import org.junit.Test; 117 | 118 | import com.in28minutes.data.api.TodoService; 119 | import com.in28minutes.data.stub.TodoServiceStub; 120 | 121 | public class TodoBusinessImplStubTest { 122 | 123 | @Test 124 | public void usingAStub() { 125 | TodoService todoService = new TodoServiceStub(); 126 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 127 | List todos = todoBusinessImpl 128 | .retrieveTodosRelatedToSpring("Ranga"); 129 | assertEquals(2, todos.size()); 130 | } 131 | } 132 | ``` 133 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 134 | ``` 135 | package com.in28minutes.data.stub; 136 | 137 | import java.util.Arrays; 138 | import java.util.List; 139 | 140 | import com.in28minutes.data.api.TodoService; 141 | 142 | public class TodoServiceStub implements TodoService { 143 | public List retrieveTodos(String user) { 144 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 145 | "Learn to Dance"); 146 | } 147 | } 148 | ``` 149 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 150 | ``` 151 | package com.in28minutes.mockito; 152 | 153 | import static org.junit.Assert.assertTrue; 154 | 155 | import org.junit.Test; 156 | 157 | public class FirstMockitoTest { 158 | 159 | @Test 160 | public void test() { 161 | assertTrue(true); 162 | } 163 | 164 | } 165 | ``` 166 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 167 | ``` 168 | package com.in28minutes.mockito; 169 | 170 | import static org.junit.Assert.assertEquals; 171 | import static org.junit.Assert.assertNull; 172 | import static org.mockito.Mockito.mock; 173 | 174 | import java.util.List; 175 | 176 | import org.junit.Test; 177 | import org.mockito.Mockito; 178 | 179 | public class ListTest { 180 | 181 | @Test 182 | public void letsMockListSize() { 183 | List list = mock(List.class); 184 | Mockito.when(list.size()).thenReturn(10); 185 | assertEquals(10, list.size()); 186 | } 187 | 188 | @Test 189 | public void letsMockListSizeWithMultipleReturnValues() { 190 | List list = mock(List.class); 191 | Mockito.when(list.size()).thenReturn(10).thenReturn(20); 192 | assertEquals(10, list.size()); // First Call 193 | assertEquals(20, list.size()); // Second Call 194 | } 195 | 196 | @Test 197 | public void letsMockListGet() { 198 | List list = mock(List.class); 199 | Mockito.when(list.get(0)).thenReturn("in28Minutes"); 200 | assertEquals("in28Minutes", list.get(0)); 201 | assertNull(list.get(1)); 202 | } 203 | 204 | @Test 205 | public void letsMockListGetWithAny() { 206 | List list = mock(List.class); 207 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 208 | // If you are using argument matchers, all arguments 209 | // have to be provided by matchers. 210 | assertEquals("in28Minutes", list.get(0)); 211 | assertEquals("in28Minutes", list.get(1)); 212 | } 213 | 214 | } 215 | ``` 216 | -------------------------------------------------------------------------------- /Step06.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Introduction to BDD 3 | - Given When Then 4 | - BDD Mockito Syntax 5 | 6 | ## Useful Snippets and References 7 | BDD : [BDD Reference](http://en.wikipedia.org/wiki/Behavior_Driven_Development) 8 | 9 | ## Exercises 10 | - Write com.in28minutes.business.TodoBusinessImplMockitoTest.usingMockito() using BDD Style. 11 | 12 | ## Files List 13 | ### /pom.xml 14 | ``` 15 | 17 | 4.0.0 18 | com.in28minutes.mockito 19 | mockito-tutorial 20 | 0.0.1-SNAPSHOT 21 | 22 | 23 | junit 24 | junit 25 | 4.12 26 | test 27 | 28 | 29 | org.mockito 30 | mockito-all 31 | 1.10.19 32 | test 33 | 34 | 35 | 36 | ``` 37 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 38 | ``` 39 | package com.in28minutes.business; 40 | 41 | import java.util.ArrayList; 42 | import java.util.List; 43 | 44 | import com.in28minutes.data.api.TodoService; 45 | 46 | public class TodoBusinessImpl { 47 | private TodoService todoService; 48 | 49 | TodoBusinessImpl(TodoService todoService) { 50 | this.todoService = todoService; 51 | } 52 | 53 | public List retrieveTodosRelatedToSpring(String user) { 54 | List filteredTodos = new ArrayList(); 55 | List allTodos = todoService.retrieveTodos(user); 56 | for (String todo : allTodos) { 57 | if (todo.contains("Spring")) { 58 | filteredTodos.add(todo); 59 | } 60 | } 61 | return filteredTodos; 62 | } 63 | } 64 | ``` 65 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 66 | ``` 67 | package com.in28minutes.data.api; 68 | 69 | import java.util.List; 70 | 71 | // External Service - Lets say this comes from WunderList 72 | public interface TodoService { 73 | public List retrieveTodos(String user); 74 | } 75 | ``` 76 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 77 | ``` 78 | package com.in28minutes.business; 79 | 80 | import static org.hamcrest.CoreMatchers.is; 81 | import static org.junit.Assert.assertEquals; 82 | import static org.junit.Assert.assertThat; 83 | import static org.mockito.BDDMockito.given; 84 | import static org.mockito.Mockito.mock; 85 | import static org.mockito.Mockito.when; 86 | 87 | import java.util.Arrays; 88 | import java.util.List; 89 | 90 | import org.junit.Test; 91 | 92 | import com.in28minutes.data.api.TodoService; 93 | 94 | public class TodoBusinessImplMockitoTest { 95 | 96 | @Test 97 | public void usingMockito() { 98 | TodoService todoService = mock(TodoService.class); 99 | List allTodos = Arrays.asList("Learn Spring MVC", 100 | "Learn Spring", "Learn to Dance"); 101 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 102 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 103 | List todos = todoBusinessImpl 104 | .retrieveTodosRelatedToSpring("Ranga"); 105 | assertEquals(2, todos.size()); 106 | } 107 | 108 | @Test 109 | public void usingMockito_UsingBDD() { 110 | TodoService todoService = mock(TodoService.class); 111 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 112 | List allTodos = Arrays.asList("Learn Spring MVC", 113 | "Learn Spring", "Learn to Dance"); 114 | 115 | //given 116 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 117 | 118 | //when 119 | List todos = todoBusinessImpl 120 | .retrieveTodosRelatedToSpring("Ranga"); 121 | 122 | //then 123 | assertThat(todos.size(), is(2)); 124 | } 125 | 126 | } 127 | ``` 128 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 129 | ``` 130 | package com.in28minutes.business; 131 | 132 | import static org.junit.Assert.assertEquals; 133 | 134 | import java.util.List; 135 | 136 | import org.junit.Test; 137 | 138 | import com.in28minutes.data.api.TodoService; 139 | import com.in28minutes.data.stub.TodoServiceStub; 140 | 141 | public class TodoBusinessImplStubTest { 142 | 143 | @Test 144 | public void usingAStub() { 145 | TodoService todoService = new TodoServiceStub(); 146 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 147 | List todos = todoBusinessImpl 148 | .retrieveTodosRelatedToSpring("Ranga"); 149 | assertEquals(2, todos.size()); 150 | } 151 | } 152 | ``` 153 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 154 | ``` 155 | package com.in28minutes.data.stub; 156 | 157 | import java.util.Arrays; 158 | import java.util.List; 159 | 160 | import com.in28minutes.data.api.TodoService; 161 | 162 | public class TodoServiceStub implements TodoService { 163 | public List retrieveTodos(String user) { 164 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 165 | "Learn to Dance"); 166 | } 167 | } 168 | ``` 169 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 170 | ``` 171 | package com.in28minutes.mockito; 172 | 173 | import static org.junit.Assert.assertTrue; 174 | 175 | import org.junit.Test; 176 | 177 | public class FirstMockitoTest { 178 | 179 | @Test 180 | public void test() { 181 | assertTrue(true); 182 | } 183 | 184 | } 185 | ``` 186 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 187 | ``` 188 | package com.in28minutes.mockito; 189 | 190 | import static org.hamcrest.CoreMatchers.is; 191 | import static org.junit.Assert.assertEquals; 192 | import static org.junit.Assert.assertNull; 193 | import static org.junit.Assert.assertThat; 194 | import static org.mockito.BDDMockito.given; 195 | import static org.mockito.Mockito.mock; 196 | 197 | import java.util.List; 198 | 199 | import org.junit.Test; 200 | import org.mockito.Mockito; 201 | 202 | public class ListTest { 203 | 204 | @Test 205 | public void letsMockListSize() { 206 | List list = mock(List.class); 207 | Mockito.when(list.size()).thenReturn(10); 208 | assertEquals(10, list.size()); 209 | } 210 | 211 | @Test 212 | public void letsMockListSizeWithMultipleReturnValues() { 213 | List list = mock(List.class); 214 | Mockito.when(list.size()).thenReturn(10).thenReturn(20); 215 | assertEquals(10, list.size()); // First Call 216 | assertEquals(20, list.size()); // Second Call 217 | } 218 | 219 | @Test 220 | public void letsMockListGet() { 221 | List list = mock(List.class); 222 | Mockito.when(list.get(0)).thenReturn("in28Minutes"); 223 | assertEquals("in28Minutes", list.get(0)); 224 | assertNull(list.get(1)); 225 | } 226 | 227 | @Test 228 | public void letsMockListGetWithAny() { 229 | List list = mock(List.class); 230 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 231 | // If you are using argument matchers, all arguments 232 | // have to be provided by matchers. 233 | assertEquals("in28Minutes", list.get(0)); 234 | assertEquals("in28Minutes", list.get(1)); 235 | } 236 | 237 | @Test 238 | public void bddAliases_UsingGivenWillReturn() { 239 | List list = mock(List.class); 240 | 241 | //given 242 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 243 | 244 | //then 245 | assertThat("in28Minutes", is(list.get(0))); 246 | assertThat("in28Minutes", is(list.get(0))); 247 | } 248 | } 249 | ``` 250 | -------------------------------------------------------------------------------- /Step07.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - How to verify calls on a mock? 3 | - Verify how many times a method is called. 4 | - We will add deleteTodo method to the TodoService. 5 | 6 | ## Useful Snippets and References 7 | First Snippet 8 | ``` 9 | verify(todoService).deleteTodo("Learn to Dance"); 10 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 11 | ``` 12 | ## Files List 13 | ### /pom.xml 14 | ``` 15 | 17 | 4.0.0 18 | com.in28minutes.mockito 19 | mockito-tutorial 20 | 0.0.1-SNAPSHOT 21 | 22 | 23 | junit 24 | junit 25 | 4.12 26 | test 27 | 28 | 29 | org.mockito 30 | mockito-all 31 | 1.10.19 32 | test 33 | 34 | 35 | 36 | ``` 37 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 38 | ``` 39 | package com.in28minutes.business; 40 | 41 | import java.util.ArrayList; 42 | import java.util.List; 43 | 44 | import com.in28minutes.data.api.TodoService; 45 | 46 | public class TodoBusinessImpl { 47 | private TodoService todoService; 48 | 49 | TodoBusinessImpl(TodoService todoService) { 50 | this.todoService = todoService; 51 | } 52 | 53 | public List retrieveTodosRelatedToSpring(String user) { 54 | List filteredTodos = new ArrayList(); 55 | List allTodos = todoService.retrieveTodos(user); 56 | for (String todo : allTodos) { 57 | if (todo.contains("Spring")) { 58 | filteredTodos.add(todo); 59 | } 60 | } 61 | return filteredTodos; 62 | } 63 | 64 | public void deleteTodosNotRelatedToSpring(String user) { 65 | List allTodos = todoService.retrieveTodos(user); 66 | for (String todo : allTodos) { 67 | if (!todo.contains("Spring")) { 68 | todoService.deleteTodo(todo); 69 | } 70 | } 71 | } 72 | } 73 | ``` 74 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 75 | ``` 76 | package com.in28minutes.data.api; 77 | 78 | import java.util.List; 79 | 80 | // External Service - Lets say this comes from WunderList 81 | public interface TodoService { 82 | 83 | public List retrieveTodos(String user); 84 | 85 | void deleteTodo(String todo); 86 | 87 | } 88 | ``` 89 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 90 | ``` 91 | package com.in28minutes.business; 92 | 93 | import static org.hamcrest.CoreMatchers.is; 94 | import static org.junit.Assert.assertEquals; 95 | import static org.junit.Assert.assertThat; 96 | import static org.mockito.BDDMockito.given; 97 | import static org.mockito.Mockito.mock; 98 | import static org.mockito.Mockito.verify; 99 | import static org.mockito.Mockito.when; 100 | 101 | import java.util.Arrays; 102 | import java.util.List; 103 | 104 | import org.junit.Test; 105 | import org.mockito.Mockito; 106 | 107 | import com.in28minutes.data.api.TodoService; 108 | 109 | public class TodoBusinessImplMockitoTest { 110 | 111 | @Test 112 | public void usingMockito() { 113 | TodoService todoService = mock(TodoService.class); 114 | List allTodos = Arrays.asList("Learn Spring MVC", 115 | "Learn Spring", "Learn to Dance"); 116 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 117 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 118 | List todos = todoBusinessImpl 119 | .retrieveTodosRelatedToSpring("Ranga"); 120 | assertEquals(2, todos.size()); 121 | } 122 | 123 | @Test 124 | public void usingMockito_UsingBDD() { 125 | TodoService todoService = mock(TodoService.class); 126 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 127 | List allTodos = Arrays.asList("Learn Spring MVC", 128 | "Learn Spring", "Learn to Dance"); 129 | 130 | //given 131 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 132 | 133 | //when 134 | List todos = todoBusinessImpl 135 | .retrieveTodosRelatedToSpring("Ranga"); 136 | 137 | //then 138 | assertThat(todos.size(), is(2)); 139 | } 140 | 141 | @Test 142 | public void letsTestDeleteNow() { 143 | 144 | TodoService todoService = mock(TodoService.class); 145 | 146 | List allTodos = Arrays.asList("Learn Spring MVC", 147 | "Learn Spring", "Learn to Dance"); 148 | 149 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 150 | 151 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 152 | 153 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 154 | 155 | verify(todoService).deleteTodo("Learn to Dance"); 156 | 157 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 158 | 159 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 160 | 161 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 162 | // atLeastOnce, atLeast 163 | 164 | } 165 | } 166 | ``` 167 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 168 | ``` 169 | package com.in28minutes.business; 170 | 171 | import static org.junit.Assert.assertEquals; 172 | 173 | import java.util.List; 174 | 175 | import org.junit.Test; 176 | 177 | import com.in28minutes.data.api.TodoService; 178 | import com.in28minutes.data.stub.TodoServiceStub; 179 | 180 | public class TodoBusinessImplStubTest { 181 | 182 | @Test 183 | public void usingAStub() { 184 | TodoService todoService = new TodoServiceStub(); 185 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 186 | List todos = todoBusinessImpl 187 | .retrieveTodosRelatedToSpring("Ranga"); 188 | assertEquals(2, todos.size()); 189 | } 190 | } 191 | ``` 192 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 193 | ``` 194 | package com.in28minutes.data.stub; 195 | 196 | import java.util.Arrays; 197 | import java.util.List; 198 | 199 | import com.in28minutes.data.api.TodoService; 200 | 201 | public class TodoServiceStub implements TodoService { 202 | public List retrieveTodos(String user) { 203 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 204 | "Learn to Dance"); 205 | } 206 | 207 | public void deleteTodo(String todo) { 208 | 209 | } 210 | } 211 | ``` 212 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 213 | ``` 214 | package com.in28minutes.mockito; 215 | 216 | import static org.junit.Assert.assertTrue; 217 | 218 | import org.junit.Test; 219 | 220 | public class FirstMockitoTest { 221 | 222 | @Test 223 | public void test() { 224 | assertTrue(true); 225 | } 226 | 227 | } 228 | ``` 229 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 230 | ``` 231 | package com.in28minutes.mockito; 232 | 233 | import static org.hamcrest.CoreMatchers.is; 234 | import static org.junit.Assert.assertEquals; 235 | import static org.junit.Assert.assertNull; 236 | import static org.junit.Assert.assertThat; 237 | import static org.mockito.BDDMockito.given; 238 | import static org.mockito.Mockito.mock; 239 | import static org.mockito.Mockito.when; 240 | 241 | import java.util.List; 242 | 243 | import org.junit.Test; 244 | import org.mockito.Mockito; 245 | 246 | public class ListTest { 247 | 248 | @Test 249 | public void letsMockListSize() { 250 | List list = mock(List.class); 251 | when(list.size()).thenReturn(10); 252 | assertEquals(10, list.size()); 253 | } 254 | 255 | @Test 256 | public void letsMockListSizeWithMultipleReturnValues() { 257 | List list = mock(List.class); 258 | when(list.size()).thenReturn(10).thenReturn(20); 259 | assertEquals(10, list.size()); // First Call 260 | assertEquals(20, list.size()); // Second Call 261 | } 262 | 263 | @Test 264 | public void letsMockListGet() { 265 | List list = mock(List.class); 266 | when(list.get(0)).thenReturn("in28Minutes"); 267 | assertEquals("in28Minutes", list.get(0)); 268 | assertNull(list.get(1)); 269 | } 270 | 271 | @Test(expected = RuntimeException.class) 272 | public void letsMockListGetToThrowException() { 273 | List list = mock(List.class); 274 | when(list.get(Mockito.anyInt())).thenThrow( 275 | new RuntimeException("Something went wrong")); 276 | list.get(0); 277 | } 278 | 279 | @Test 280 | public void letsMockListGetWithAny() { 281 | List list = mock(List.class); 282 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 283 | // If you are using argument matchers, all arguments 284 | // have to be provided by matchers. 285 | assertEquals("in28Minutes", list.get(0)); 286 | assertEquals("in28Minutes", list.get(1)); 287 | } 288 | 289 | @Test 290 | public void bddAliases_UsingGivenWillReturn() { 291 | List list = mock(List.class); 292 | 293 | //given 294 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 295 | 296 | //then 297 | assertThat("in28Minutes", is(list.get(0))); 298 | assertThat("in28Minutes", is(list.get(0))); 299 | } 300 | } 301 | ``` 302 | -------------------------------------------------------------------------------- /Step08.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - How to capture an argument which is passed to a mock? 3 | 4 | ## Useful Snippets and References 5 | First Snippet 6 | ``` 7 | @Test 8 | public void captureArgument() { 9 | ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(String.class); 10 | 11 | TodoService todoService = mock(TodoService.class); 12 | 13 | List allTodos = Arrays.asList("Learn Spring MVC", "Learn Spring", "Learn to Dance"); 14 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 15 | 16 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 17 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 18 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 19 | 20 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 21 | } 22 | ``` 23 | ## Files List 24 | ### /pom.xml 25 | ``` 26 | 28 | 4.0.0 29 | com.in28minutes.mockito 30 | mockito-tutorial 31 | 0.0.1-SNAPSHOT 32 | 33 | 34 | junit 35 | junit 36 | 4.12 37 | test 38 | 39 | 40 | org.mockito 41 | mockito-all 42 | 1.10.19 43 | test 44 | 45 | 46 | 47 | ``` 48 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 49 | ``` 50 | package com.in28minutes.business; 51 | 52 | import java.util.ArrayList; 53 | import java.util.List; 54 | 55 | import com.in28minutes.data.api.TodoService; 56 | 57 | public class TodoBusinessImpl { 58 | private TodoService todoService; 59 | 60 | TodoBusinessImpl(TodoService todoService) { 61 | this.todoService = todoService; 62 | } 63 | 64 | public List retrieveTodosRelatedToSpring(String user) { 65 | List filteredTodos = new ArrayList(); 66 | List allTodos = todoService.retrieveTodos(user); 67 | for (String todo : allTodos) { 68 | if (todo.contains("Spring")) { 69 | filteredTodos.add(todo); 70 | } 71 | } 72 | return filteredTodos; 73 | } 74 | 75 | public void deleteTodosNotRelatedToSpring(String user) { 76 | List allTodos = todoService.retrieveTodos(user); 77 | for (String todo : allTodos) { 78 | if (!todo.contains("Spring")) { 79 | todoService.deleteTodo(todo); 80 | } 81 | } 82 | } 83 | } 84 | ``` 85 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 86 | ``` 87 | package com.in28minutes.data.api; 88 | 89 | import java.util.List; 90 | 91 | // External Service - Lets say this comes from WunderList 92 | public interface TodoService { 93 | 94 | public List retrieveTodos(String user); 95 | 96 | void deleteTodo(String todo); 97 | 98 | } 99 | ``` 100 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 101 | ``` 102 | package com.in28minutes.business; 103 | 104 | import static org.hamcrest.CoreMatchers.is; 105 | import static org.junit.Assert.assertEquals; 106 | import static org.junit.Assert.assertThat; 107 | import static org.mockito.BDDMockito.given; 108 | import static org.mockito.Mockito.mock; 109 | import static org.mockito.Mockito.verify; 110 | import static org.mockito.Mockito.when; 111 | 112 | import java.util.Arrays; 113 | import java.util.List; 114 | 115 | import org.junit.Test; 116 | import org.mockito.ArgumentCaptor; 117 | import org.mockito.Mockito; 118 | 119 | import com.in28minutes.data.api.TodoService; 120 | 121 | public class TodoBusinessImplMockitoTest { 122 | 123 | @Test 124 | public void usingMockito() { 125 | TodoService todoService = mock(TodoService.class); 126 | List allTodos = Arrays.asList("Learn Spring MVC", 127 | "Learn Spring", "Learn to Dance"); 128 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 129 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 130 | List todos = todoBusinessImpl 131 | .retrieveTodosRelatedToSpring("Ranga"); 132 | assertEquals(2, todos.size()); 133 | } 134 | 135 | @Test 136 | public void usingMockito_UsingBDD() { 137 | TodoService todoService = mock(TodoService.class); 138 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 139 | List allTodos = Arrays.asList("Learn Spring MVC", 140 | "Learn Spring", "Learn to Dance"); 141 | 142 | //given 143 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 144 | 145 | //when 146 | List todos = todoBusinessImpl 147 | .retrieveTodosRelatedToSpring("Ranga"); 148 | 149 | //then 150 | assertThat(todos.size(), is(2)); 151 | } 152 | 153 | @Test 154 | public void letsTestDeleteNow() { 155 | 156 | TodoService todoService = mock(TodoService.class); 157 | 158 | List allTodos = Arrays.asList("Learn Spring MVC", 159 | "Learn Spring", "Learn to Dance"); 160 | 161 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 162 | 163 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 164 | 165 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 166 | 167 | verify(todoService).deleteTodo("Learn to Dance"); 168 | 169 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 170 | 171 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 172 | 173 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 174 | // atLeastOnce, atLeast 175 | 176 | } 177 | 178 | @Test 179 | public void captureArgument() { 180 | ArgumentCaptor argumentCaptor = ArgumentCaptor 181 | .forClass(String.class); 182 | 183 | TodoService todoService = mock(TodoService.class); 184 | 185 | List allTodos = Arrays.asList("Learn Spring MVC", 186 | "Learn Spring", "Learn to Dance"); 187 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 188 | 189 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 190 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 191 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 192 | 193 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 194 | } 195 | } 196 | ``` 197 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 198 | ``` 199 | package com.in28minutes.business; 200 | 201 | import static org.junit.Assert.assertEquals; 202 | 203 | import java.util.List; 204 | 205 | import org.junit.Test; 206 | 207 | import com.in28minutes.data.api.TodoService; 208 | import com.in28minutes.data.stub.TodoServiceStub; 209 | 210 | public class TodoBusinessImplStubTest { 211 | 212 | @Test 213 | public void usingAStub() { 214 | TodoService todoService = new TodoServiceStub(); 215 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 216 | List todos = todoBusinessImpl 217 | .retrieveTodosRelatedToSpring("Ranga"); 218 | assertEquals(2, todos.size()); 219 | } 220 | } 221 | ``` 222 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 223 | ``` 224 | package com.in28minutes.data.stub; 225 | 226 | import java.util.Arrays; 227 | import java.util.List; 228 | 229 | import com.in28minutes.data.api.TodoService; 230 | 231 | public class TodoServiceStub implements TodoService { 232 | public List retrieveTodos(String user) { 233 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 234 | "Learn to Dance"); 235 | } 236 | 237 | public void deleteTodo(String todo) { 238 | 239 | } 240 | } 241 | ``` 242 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 243 | ``` 244 | package com.in28minutes.mockito; 245 | 246 | import static org.junit.Assert.assertTrue; 247 | 248 | import org.junit.Test; 249 | 250 | public class FirstMockitoTest { 251 | 252 | @Test 253 | public void test() { 254 | assertTrue(true); 255 | } 256 | 257 | } 258 | ``` 259 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 260 | ``` 261 | package com.in28minutes.mockito; 262 | 263 | import static org.hamcrest.CoreMatchers.is; 264 | import static org.junit.Assert.assertEquals; 265 | import static org.junit.Assert.assertNull; 266 | import static org.junit.Assert.assertThat; 267 | import static org.mockito.BDDMockito.given; 268 | import static org.mockito.Mockito.mock; 269 | import static org.mockito.Mockito.when; 270 | 271 | import java.util.List; 272 | 273 | import org.junit.Test; 274 | import org.mockito.Mockito; 275 | 276 | public class ListTest { 277 | 278 | @Test 279 | public void letsMockListSize() { 280 | List list = mock(List.class); 281 | when(list.size()).thenReturn(10); 282 | assertEquals(10, list.size()); 283 | } 284 | 285 | @Test 286 | public void letsMockListSizeWithMultipleReturnValues() { 287 | List list = mock(List.class); 288 | when(list.size()).thenReturn(10).thenReturn(20); 289 | assertEquals(10, list.size()); // First Call 290 | assertEquals(20, list.size()); // Second Call 291 | } 292 | 293 | @Test 294 | public void letsMockListGet() { 295 | List list = mock(List.class); 296 | when(list.get(0)).thenReturn("in28Minutes"); 297 | assertEquals("in28Minutes", list.get(0)); 298 | assertNull(list.get(1)); 299 | } 300 | 301 | @Test(expected = RuntimeException.class) 302 | public void letsMockListGetToThrowException() { 303 | List list = mock(List.class); 304 | when(list.get(Mockito.anyInt())).thenThrow( 305 | new RuntimeException("Something went wrong")); 306 | list.get(0); 307 | } 308 | 309 | @Test 310 | public void letsMockListGetWithAny() { 311 | List list = mock(List.class); 312 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 313 | // If you are using argument matchers, all arguments 314 | // have to be provided by matchers. 315 | assertEquals("in28Minutes", list.get(0)); 316 | assertEquals("in28Minutes", list.get(1)); 317 | } 318 | 319 | @Test 320 | public void bddAliases_UsingGivenWillReturn() { 321 | List list = mock(List.class); 322 | 323 | //given 324 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 325 | 326 | //then 327 | assertThat("in28Minutes", is(list.get(0))); 328 | assertThat("in28Minutes", is(list.get(0))); 329 | } 330 | } 331 | ``` 332 | -------------------------------------------------------------------------------- /Step09.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Hamcrest Matchers 3 | 4 | ## Useful Snippets and References 5 | - Set up static import for 6 | ``` 7 | import static org.hamcrest.CoreMatchers.hasItems; 8 | ``` 9 | 10 | - First Snippet 11 | ``` 12 | 13 | org.hamcrest 14 | hamcrest-library 15 | 1.3 16 | test 17 | 18 | ``` 19 | 20 | - Code Snippets 21 | ``` 22 | assertThat(scores, hasSize(4)); 23 | assertThat(scores, hasItems(100, 101)); 24 | assertThat(scores, everyItem(greaterThan(90))); 25 | assertThat(scores, everyItem(lessThan(200))); 26 | 27 | // String 28 | assertThat("", isEmptyString()); 29 | assertThat(null, isEmptyOrNullString()); 30 | ``` 31 | 32 | ## Files List 33 | ### /pom.xml 34 | ``` 35 | 37 | 4.0.0 38 | com.in28minutes.mockito 39 | mockito-tutorial 40 | 0.0.1-SNAPSHOT 41 | 42 | 43 | junit 44 | junit 45 | 4.12 46 | test 47 | 48 | 49 | org.mockito 50 | mockito-all 51 | 1.10.19 52 | test 53 | 54 | 55 | org.hamcrest 56 | hamcrest-library 57 | 1.3 58 | test 59 | 60 | 61 | 62 | ``` 63 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 64 | ``` 65 | package com.in28minutes.business; 66 | 67 | import java.util.ArrayList; 68 | import java.util.List; 69 | 70 | import com.in28minutes.data.api.TodoService; 71 | 72 | public class TodoBusinessImpl { 73 | private TodoService todoService; 74 | 75 | TodoBusinessImpl(TodoService todoService) { 76 | this.todoService = todoService; 77 | } 78 | 79 | public List retrieveTodosRelatedToSpring(String user) { 80 | List filteredTodos = new ArrayList(); 81 | List allTodos = todoService.retrieveTodos(user); 82 | for (String todo : allTodos) { 83 | if (todo.contains("Spring")) { 84 | filteredTodos.add(todo); 85 | } 86 | } 87 | return filteredTodos; 88 | } 89 | 90 | public void deleteTodosNotRelatedToSpring(String user) { 91 | List allTodos = todoService.retrieveTodos(user); 92 | for (String todo : allTodos) { 93 | if (!todo.contains("Spring")) { 94 | todoService.deleteTodo(todo); 95 | } 96 | } 97 | } 98 | } 99 | ``` 100 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 101 | ``` 102 | package com.in28minutes.data.api; 103 | 104 | import java.util.List; 105 | 106 | // External Service - Lets say this comes from WunderList 107 | public interface TodoService { 108 | 109 | public List retrieveTodos(String user); 110 | 111 | void deleteTodo(String todo); 112 | 113 | } 114 | ``` 115 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 116 | ``` 117 | package com.in28minutes.business; 118 | 119 | import static org.hamcrest.CoreMatchers.is; 120 | import static org.junit.Assert.assertEquals; 121 | import static org.junit.Assert.assertThat; 122 | import static org.mockito.BDDMockito.given; 123 | import static org.mockito.Mockito.mock; 124 | import static org.mockito.Mockito.verify; 125 | import static org.mockito.Mockito.when; 126 | 127 | import java.util.Arrays; 128 | import java.util.List; 129 | 130 | import org.junit.Test; 131 | import org.mockito.ArgumentCaptor; 132 | import org.mockito.Mockito; 133 | 134 | import com.in28minutes.data.api.TodoService; 135 | 136 | public class TodoBusinessImplMockitoTest { 137 | 138 | @Test 139 | public void usingMockito() { 140 | TodoService todoService = mock(TodoService.class); 141 | List allTodos = Arrays.asList("Learn Spring MVC", 142 | "Learn Spring", "Learn to Dance"); 143 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 144 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 145 | List todos = todoBusinessImpl 146 | .retrieveTodosRelatedToSpring("Ranga"); 147 | assertEquals(2, todos.size()); 148 | } 149 | 150 | @Test 151 | public void usingMockito_UsingBDD() { 152 | TodoService todoService = mock(TodoService.class); 153 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 154 | List allTodos = Arrays.asList("Learn Spring MVC", 155 | "Learn Spring", "Learn to Dance"); 156 | 157 | //given 158 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 159 | 160 | //when 161 | List todos = todoBusinessImpl 162 | .retrieveTodosRelatedToSpring("Ranga"); 163 | 164 | //then 165 | assertThat(todos.size(), is(2)); 166 | } 167 | 168 | @Test 169 | public void letsTestDeleteNow() { 170 | 171 | TodoService todoService = mock(TodoService.class); 172 | 173 | List allTodos = Arrays.asList("Learn Spring MVC", 174 | "Learn Spring", "Learn to Dance"); 175 | 176 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 177 | 178 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 179 | 180 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 181 | 182 | verify(todoService).deleteTodo("Learn to Dance"); 183 | 184 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 185 | 186 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 187 | 188 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 189 | // atLeastOnce, atLeast 190 | 191 | } 192 | 193 | @Test 194 | public void captureArgument() { 195 | ArgumentCaptor argumentCaptor = ArgumentCaptor 196 | .forClass(String.class); 197 | 198 | TodoService todoService = mock(TodoService.class); 199 | 200 | List allTodos = Arrays.asList("Learn Spring MVC", 201 | "Learn Spring", "Learn to Dance"); 202 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 203 | 204 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 205 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 206 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 207 | 208 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 209 | } 210 | } 211 | ``` 212 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 213 | ``` 214 | package com.in28minutes.business; 215 | 216 | import static org.junit.Assert.assertEquals; 217 | 218 | import java.util.List; 219 | 220 | import org.junit.Test; 221 | 222 | import com.in28minutes.data.api.TodoService; 223 | import com.in28minutes.data.stub.TodoServiceStub; 224 | 225 | public class TodoBusinessImplStubTest { 226 | 227 | @Test 228 | public void usingAStub() { 229 | TodoService todoService = new TodoServiceStub(); 230 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 231 | List todos = todoBusinessImpl 232 | .retrieveTodosRelatedToSpring("Ranga"); 233 | assertEquals(2, todos.size()); 234 | } 235 | } 236 | ``` 237 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 238 | ``` 239 | package com.in28minutes.data.stub; 240 | 241 | import java.util.Arrays; 242 | import java.util.List; 243 | 244 | import com.in28minutes.data.api.TodoService; 245 | 246 | public class TodoServiceStub implements TodoService { 247 | public List retrieveTodos(String user) { 248 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 249 | "Learn to Dance"); 250 | } 251 | 252 | public void deleteTodo(String todo) { 253 | 254 | } 255 | } 256 | ``` 257 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 258 | ``` 259 | package com.in28minutes.mockito; 260 | 261 | import static org.junit.Assert.assertTrue; 262 | 263 | import org.junit.Test; 264 | 265 | public class FirstMockitoTest { 266 | 267 | @Test 268 | public void test() { 269 | assertTrue(true); 270 | } 271 | 272 | } 273 | ``` 274 | ### /src/test/java/com/in28minutes/mockito/HamcrestMatcherTest.java 275 | ``` 276 | package com.in28minutes.mockito; 277 | 278 | import static org.hamcrest.CoreMatchers.hasItems; 279 | import static org.hamcrest.MatcherAssert.assertThat; 280 | import static org.hamcrest.Matchers.arrayContainingInAnyOrder; 281 | import static org.hamcrest.Matchers.arrayWithSize; 282 | import static org.hamcrest.Matchers.greaterThan; 283 | import static org.hamcrest.Matchers.hasSize; 284 | import static org.hamcrest.Matchers.isEmptyOrNullString; 285 | import static org.hamcrest.Matchers.isEmptyString; 286 | import static org.hamcrest.Matchers.lessThan; 287 | import static org.hamcrest.core.Every.everyItem; 288 | 289 | import java.util.Arrays; 290 | import java.util.List; 291 | 292 | import org.junit.Test; 293 | 294 | public class HamcrestMatcherTest { 295 | 296 | @Test 297 | public void basicHamcrestMatchers() { 298 | List scores = Arrays.asList(99, 100, 101, 105); 299 | assertThat(scores, hasSize(4)); 300 | assertThat(scores, hasItems(100, 101)); 301 | assertThat(scores, everyItem(greaterThan(90))); 302 | assertThat(scores, everyItem(lessThan(200))); 303 | 304 | // String 305 | assertThat("", isEmptyString()); 306 | assertThat(null, isEmptyOrNullString()); 307 | 308 | // Array 309 | Integer[] marks = { 1, 2, 3 }; 310 | 311 | assertThat(marks, arrayWithSize(3)); 312 | assertThat(marks, arrayContainingInAnyOrder(2, 3, 1)); 313 | 314 | } 315 | } 316 | ``` 317 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 318 | ``` 319 | package com.in28minutes.mockito; 320 | 321 | import static org.hamcrest.CoreMatchers.is; 322 | import static org.junit.Assert.assertEquals; 323 | import static org.junit.Assert.assertNull; 324 | import static org.junit.Assert.assertThat; 325 | import static org.mockito.BDDMockito.given; 326 | import static org.mockito.Mockito.mock; 327 | import static org.mockito.Mockito.when; 328 | 329 | import java.util.List; 330 | 331 | import org.junit.Test; 332 | import org.mockito.Mockito; 333 | 334 | public class ListTest { 335 | 336 | @Test 337 | public void letsMockListSize() { 338 | List list = mock(List.class); 339 | when(list.size()).thenReturn(10); 340 | assertEquals(10, list.size()); 341 | } 342 | 343 | @Test 344 | public void letsMockListSizeWithMultipleReturnValues() { 345 | List list = mock(List.class); 346 | when(list.size()).thenReturn(10).thenReturn(20); 347 | assertEquals(10, list.size()); // First Call 348 | assertEquals(20, list.size()); // Second Call 349 | } 350 | 351 | @Test 352 | public void letsMockListGet() { 353 | List list = mock(List.class); 354 | when(list.get(0)).thenReturn("in28Minutes"); 355 | assertEquals("in28Minutes", list.get(0)); 356 | assertNull(list.get(1)); 357 | } 358 | 359 | @Test(expected = RuntimeException.class) 360 | public void letsMockListGetToThrowException() { 361 | List list = mock(List.class); 362 | when(list.get(Mockito.anyInt())).thenThrow( 363 | new RuntimeException("Something went wrong")); 364 | list.get(0); 365 | } 366 | 367 | @Test 368 | public void letsMockListGetWithAny() { 369 | List list = mock(List.class); 370 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 371 | // If you are using argument matchers, all arguments 372 | // have to be provided by matchers. 373 | assertEquals("in28Minutes", list.get(0)); 374 | assertEquals("in28Minutes", list.get(1)); 375 | } 376 | 377 | @Test 378 | public void bddAliases_UsingGivenWillReturn() { 379 | List list = mock(List.class); 380 | 381 | //given 382 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 383 | 384 | //then 385 | assertThat("in28Minutes", is(list.get(0))); 386 | assertThat("in28Minutes", is(list.get(0))); 387 | } 388 | } 389 | ``` 390 | -------------------------------------------------------------------------------- /Step10.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Mockito Annotations 3 | - @Mock 4 | - @InjectMocks 5 | - @RunWith(MockitoJUnitRunner.class) 6 | - @Captor 7 | 8 | ## Files List 9 | ### /pom.xml 10 | ``` 11 | 13 | 4.0.0 14 | com.in28minutes.mockito 15 | mockito-tutorial 16 | 0.0.1-SNAPSHOT 17 | 18 | 19 | junit 20 | junit 21 | 4.12 22 | test 23 | 24 | 25 | org.mockito 26 | mockito-all 27 | 1.10.19 28 | test 29 | 30 | 31 | org.hamcrest 32 | hamcrest-library 33 | 1.3 34 | test 35 | 36 | 37 | 38 | ``` 39 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 40 | ``` 41 | package com.in28minutes.business; 42 | 43 | import java.util.ArrayList; 44 | import java.util.List; 45 | 46 | import com.in28minutes.data.api.TodoService; 47 | 48 | public class TodoBusinessImpl { 49 | private TodoService todoService; 50 | 51 | TodoBusinessImpl(TodoService todoService) { 52 | this.todoService = todoService; 53 | } 54 | 55 | public List retrieveTodosRelatedToSpring(String user) { 56 | List filteredTodos = new ArrayList(); 57 | List allTodos = todoService.retrieveTodos(user); 58 | for (String todo : allTodos) { 59 | if (todo.contains("Spring")) { 60 | filteredTodos.add(todo); 61 | } 62 | } 63 | return filteredTodos; 64 | } 65 | 66 | public void deleteTodosNotRelatedToSpring(String user) { 67 | List allTodos = todoService.retrieveTodos(user); 68 | for (String todo : allTodos) { 69 | if (!todo.contains("Spring")) { 70 | todoService.deleteTodo(todo); 71 | } 72 | } 73 | } 74 | } 75 | ``` 76 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 77 | ``` 78 | package com.in28minutes.data.api; 79 | 80 | import java.util.List; 81 | 82 | // External Service - Lets say this comes from WunderList 83 | public interface TodoService { 84 | 85 | public List retrieveTodos(String user); 86 | 87 | void deleteTodo(String todo); 88 | 89 | } 90 | ``` 91 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoInjectMocksTest.java 92 | ``` 93 | package com.in28minutes.business; 94 | 95 | import static org.hamcrest.CoreMatchers.is; 96 | import static org.junit.Assert.assertEquals; 97 | import static org.junit.Assert.assertThat; 98 | import static org.mockito.BDDMockito.given; 99 | import static org.mockito.Mockito.verify; 100 | import static org.mockito.Mockito.when; 101 | 102 | import java.util.Arrays; 103 | import java.util.List; 104 | 105 | import org.junit.Test; 106 | import org.junit.runner.RunWith; 107 | import org.mockito.ArgumentCaptor; 108 | import org.mockito.Captor; 109 | import org.mockito.InjectMocks; 110 | import org.mockito.Mock; 111 | import org.mockito.Mockito; 112 | import org.mockito.runners.MockitoJUnitRunner; 113 | 114 | import com.in28minutes.data.api.TodoService; 115 | 116 | @RunWith(MockitoJUnitRunner.class) 117 | public class TodoBusinessImplMockitoInjectMocksTest { 118 | @Mock 119 | TodoService todoService; 120 | 121 | @InjectMocks 122 | TodoBusinessImpl todoBusinessImpl; 123 | 124 | @Captor 125 | ArgumentCaptor stringArgumentCaptor; 126 | 127 | @Test 128 | public void usingMockito() { 129 | List allTodos = Arrays.asList("Learn Spring MVC", 130 | "Learn Spring", "Learn to Dance"); 131 | 132 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 133 | 134 | List todos = todoBusinessImpl 135 | .retrieveTodosRelatedToSpring("Ranga"); 136 | assertEquals(2, todos.size()); 137 | } 138 | 139 | @Test 140 | public void usingMockito_UsingBDD() { 141 | List allTodos = Arrays.asList("Learn Spring MVC", 142 | "Learn Spring", "Learn to Dance"); 143 | 144 | //given 145 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 146 | 147 | //when 148 | List todos = todoBusinessImpl 149 | .retrieveTodosRelatedToSpring("Ranga"); 150 | 151 | //then 152 | assertThat(todos.size(), is(2)); 153 | } 154 | 155 | @Test 156 | public void letsTestDeleteNow() { 157 | 158 | List allTodos = Arrays.asList("Learn Spring MVC", 159 | "Learn Spring", "Learn to Dance"); 160 | 161 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 162 | 163 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 164 | 165 | verify(todoService).deleteTodo("Learn to Dance"); 166 | 167 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 168 | 169 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 170 | 171 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 172 | // atLeastOnce, atLeast 173 | 174 | } 175 | 176 | @Test 177 | public void captureArgument() { 178 | List allTodos = Arrays.asList("Learn Spring MVC", 179 | "Learn Spring", "Learn to Dance"); 180 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 181 | 182 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 183 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 184 | 185 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 186 | } 187 | } 188 | ``` 189 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 190 | ``` 191 | package com.in28minutes.business; 192 | 193 | import static org.hamcrest.CoreMatchers.is; 194 | import static org.junit.Assert.assertEquals; 195 | import static org.junit.Assert.assertThat; 196 | import static org.mockito.BDDMockito.given; 197 | import static org.mockito.Mockito.mock; 198 | import static org.mockito.Mockito.verify; 199 | import static org.mockito.Mockito.when; 200 | 201 | import java.util.Arrays; 202 | import java.util.List; 203 | 204 | import org.junit.Test; 205 | import org.mockito.ArgumentCaptor; 206 | import org.mockito.Mockito; 207 | 208 | import com.in28minutes.data.api.TodoService; 209 | 210 | public class TodoBusinessImplMockitoTest { 211 | 212 | @Test 213 | public void usingMockito() { 214 | TodoService todoService = mock(TodoService.class); 215 | List allTodos = Arrays.asList("Learn Spring MVC", 216 | "Learn Spring", "Learn to Dance"); 217 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 218 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 219 | List todos = todoBusinessImpl 220 | .retrieveTodosRelatedToSpring("Ranga"); 221 | assertEquals(2, todos.size()); 222 | } 223 | 224 | @Test 225 | public void usingMockito_UsingBDD() { 226 | TodoService todoService = mock(TodoService.class); 227 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 228 | List allTodos = Arrays.asList("Learn Spring MVC", 229 | "Learn Spring", "Learn to Dance"); 230 | 231 | //given 232 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 233 | 234 | //when 235 | List todos = todoBusinessImpl 236 | .retrieveTodosRelatedToSpring("Ranga"); 237 | 238 | //then 239 | assertThat(todos.size(), is(2)); 240 | } 241 | 242 | @Test 243 | public void letsTestDeleteNow() { 244 | 245 | TodoService todoService = mock(TodoService.class); 246 | 247 | List allTodos = Arrays.asList("Learn Spring MVC", 248 | "Learn Spring", "Learn to Dance"); 249 | 250 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 251 | 252 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 253 | 254 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 255 | 256 | verify(todoService).deleteTodo("Learn to Dance"); 257 | 258 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 259 | 260 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 261 | 262 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 263 | // atLeastOnce, atLeast 264 | 265 | } 266 | 267 | @Test 268 | public void captureArgument() { 269 | ArgumentCaptor argumentCaptor = ArgumentCaptor 270 | .forClass(String.class); 271 | 272 | TodoService todoService = mock(TodoService.class); 273 | 274 | List allTodos = Arrays.asList("Learn Spring MVC", 275 | "Learn Spring", "Learn to Dance"); 276 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 277 | 278 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 279 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 280 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 281 | 282 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 283 | } 284 | } 285 | ``` 286 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 287 | ``` 288 | package com.in28minutes.business; 289 | 290 | import static org.junit.Assert.assertEquals; 291 | 292 | import java.util.List; 293 | 294 | import org.junit.Test; 295 | 296 | import com.in28minutes.data.api.TodoService; 297 | import com.in28minutes.data.stub.TodoServiceStub; 298 | 299 | public class TodoBusinessImplStubTest { 300 | 301 | @Test 302 | public void usingAStub() { 303 | TodoService todoService = new TodoServiceStub(); 304 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 305 | List todos = todoBusinessImpl 306 | .retrieveTodosRelatedToSpring("Ranga"); 307 | assertEquals(2, todos.size()); 308 | } 309 | } 310 | ``` 311 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 312 | ``` 313 | package com.in28minutes.data.stub; 314 | 315 | import java.util.Arrays; 316 | import java.util.List; 317 | 318 | import com.in28minutes.data.api.TodoService; 319 | 320 | public class TodoServiceStub implements TodoService { 321 | public List retrieveTodos(String user) { 322 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 323 | "Learn to Dance"); 324 | } 325 | 326 | public void deleteTodo(String todo) { 327 | 328 | } 329 | } 330 | ``` 331 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 332 | ``` 333 | package com.in28minutes.mockito; 334 | 335 | import static org.junit.Assert.assertTrue; 336 | 337 | import org.junit.Test; 338 | 339 | public class FirstMockitoTest { 340 | 341 | @Test 342 | public void test() { 343 | assertTrue(true); 344 | } 345 | 346 | } 347 | ``` 348 | ### /src/test/java/com/in28minutes/mockito/HamcrestMatcherTest.java 349 | ``` 350 | package com.in28minutes.mockito; 351 | 352 | import static org.hamcrest.CoreMatchers.hasItems; 353 | import static org.hamcrest.MatcherAssert.assertThat; 354 | import static org.hamcrest.Matchers.arrayContainingInAnyOrder; 355 | import static org.hamcrest.Matchers.arrayWithSize; 356 | import static org.hamcrest.Matchers.greaterThan; 357 | import static org.hamcrest.Matchers.hasSize; 358 | import static org.hamcrest.Matchers.isEmptyOrNullString; 359 | import static org.hamcrest.Matchers.isEmptyString; 360 | import static org.hamcrest.Matchers.lessThan; 361 | import static org.hamcrest.core.Every.everyItem; 362 | 363 | import java.util.Arrays; 364 | import java.util.List; 365 | 366 | import org.junit.Test; 367 | 368 | public class HamcrestMatcherTest { 369 | 370 | @Test 371 | public void basicHamcrestMatchers() { 372 | List scores = Arrays.asList(99, 100, 101, 105); 373 | assertThat(scores, hasSize(4)); 374 | assertThat(scores, hasItems(100, 101)); 375 | assertThat(scores, everyItem(greaterThan(90))); 376 | assertThat(scores, everyItem(lessThan(200))); 377 | 378 | // String 379 | assertThat("", isEmptyString()); 380 | assertThat(null, isEmptyOrNullString()); 381 | 382 | // Array 383 | Integer[] marks = { 1, 2, 3 }; 384 | 385 | assertThat(marks, arrayWithSize(3)); 386 | assertThat(marks, arrayContainingInAnyOrder(2, 3, 1)); 387 | 388 | } 389 | } 390 | ``` 391 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 392 | ``` 393 | package com.in28minutes.mockito; 394 | 395 | import static org.hamcrest.CoreMatchers.is; 396 | import static org.junit.Assert.assertEquals; 397 | import static org.junit.Assert.assertNull; 398 | import static org.junit.Assert.assertThat; 399 | import static org.mockito.BDDMockito.given; 400 | import static org.mockito.Mockito.mock; 401 | import static org.mockito.Mockito.when; 402 | 403 | import java.util.List; 404 | 405 | import org.junit.Test; 406 | import org.mockito.Mockito; 407 | 408 | public class ListTest { 409 | 410 | @Test 411 | public void letsMockListSize() { 412 | List list = mock(List.class); 413 | when(list.size()).thenReturn(10); 414 | assertEquals(10, list.size()); 415 | } 416 | 417 | @Test 418 | public void letsMockListSizeWithMultipleReturnValues() { 419 | List list = mock(List.class); 420 | when(list.size()).thenReturn(10).thenReturn(20); 421 | assertEquals(10, list.size()); // First Call 422 | assertEquals(20, list.size()); // Second Call 423 | } 424 | 425 | @Test 426 | public void letsMockListGet() { 427 | List list = mock(List.class); 428 | when(list.get(0)).thenReturn("in28Minutes"); 429 | assertEquals("in28Minutes", list.get(0)); 430 | assertNull(list.get(1)); 431 | } 432 | 433 | @Test(expected = RuntimeException.class) 434 | public void letsMockListGetToThrowException() { 435 | List list = mock(List.class); 436 | when(list.get(Mockito.anyInt())).thenThrow( 437 | new RuntimeException("Something went wrong")); 438 | list.get(0); 439 | } 440 | 441 | @Test 442 | public void letsMockListGetWithAny() { 443 | List list = mock(List.class); 444 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 445 | // If you are using argument matchers, all arguments 446 | // have to be provided by matchers. 447 | assertEquals("in28Minutes", list.get(0)); 448 | assertEquals("in28Minutes", list.get(1)); 449 | } 450 | 451 | @Test 452 | public void bddAliases_UsingGivenWillReturn() { 453 | List list = mock(List.class); 454 | 455 | //given 456 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 457 | 458 | //then 459 | assertThat("in28Minutes", is(list.get(0))); 460 | assertThat("in28Minutes", is(list.get(0))); 461 | } 462 | } 463 | ``` 464 | -------------------------------------------------------------------------------- /Step11.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - JUnit Rules. Using MockitoJUnit.rule() instead of @RunWith(MockitoJUnitRunner.class). 3 | 4 | ## Useful Snippets and References 5 | First Snippet 6 | ``` 7 | @Rule 8 | public MockitoRule mockitoRule = MockitoJUnit.rule(); 9 | ``` 10 | Second Snippet 11 | ``` 12 | ``` 13 | 14 | ## Files List 15 | ### /pom.xml 16 | ``` 17 | 19 | 4.0.0 20 | com.in28minutes.mockito 21 | mockito-tutorial 22 | 0.0.1-SNAPSHOT 23 | 24 | 25 | junit 26 | junit 27 | 4.12 28 | test 29 | 30 | 31 | org.mockito 32 | mockito-all 33 | 1.10.19 34 | test 35 | 36 | 37 | org.hamcrest 38 | hamcrest-library 39 | 1.3 40 | test 41 | 42 | 43 | 44 | ``` 45 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 46 | ``` 47 | package com.in28minutes.business; 48 | 49 | import java.util.ArrayList; 50 | import java.util.List; 51 | 52 | import com.in28minutes.data.api.TodoService; 53 | 54 | public class TodoBusinessImpl { 55 | 56 | private TodoService todoService; 57 | 58 | TodoBusinessImpl(TodoService todoService) { 59 | this.todoService = todoService; 60 | } 61 | 62 | public List retrieveTodosRelatedToSpring(String user) { 63 | List filteredTodos = new ArrayList(); 64 | List allTodos = todoService.retrieveTodos(user); 65 | for (String todo : allTodos) { 66 | if (todo.contains("Spring")) { 67 | filteredTodos.add(todo); 68 | } 69 | } 70 | return filteredTodos; 71 | } 72 | 73 | public void deleteTodosNotRelatedToSpring(String user) { 74 | List allTodos = todoService.retrieveTodos(user); 75 | for (String todo : allTodos) { 76 | if (!todo.contains("Spring")) { 77 | todoService.deleteTodo(todo); 78 | } 79 | } 80 | } 81 | } 82 | ``` 83 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 84 | ``` 85 | package com.in28minutes.data.api; 86 | 87 | import java.util.List; 88 | 89 | // External Service - Lets say this comes from WunderList 90 | public interface TodoService { 91 | 92 | public List retrieveTodos(String user); 93 | 94 | void deleteTodo(String todo); 95 | 96 | } 97 | ``` 98 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoInjectMocksTest.java 99 | ``` 100 | package com.in28minutes.business; 101 | 102 | import static org.hamcrest.CoreMatchers.is; 103 | import static org.junit.Assert.assertEquals; 104 | import static org.junit.Assert.assertThat; 105 | import static org.mockito.BDDMockito.given; 106 | import static org.mockito.Mockito.verify; 107 | import static org.mockito.Mockito.when; 108 | 109 | import java.util.Arrays; 110 | import java.util.List; 111 | 112 | import org.junit.Test; 113 | import org.junit.runner.RunWith; 114 | import org.mockito.ArgumentCaptor; 115 | import org.mockito.Captor; 116 | import org.mockito.InjectMocks; 117 | import org.mockito.Mock; 118 | import org.mockito.Mockito; 119 | import org.mockito.runners.MockitoJUnitRunner; 120 | 121 | import com.in28minutes.data.api.TodoService; 122 | 123 | @RunWith(MockitoJUnitRunner.class) 124 | public class TodoBusinessImplMockitoInjectMocksTest { 125 | @Mock 126 | TodoService todoService; 127 | 128 | @InjectMocks 129 | TodoBusinessImpl todoBusinessImpl; 130 | 131 | @Captor 132 | ArgumentCaptor stringArgumentCaptor; 133 | 134 | @Test 135 | public void usingMockito() { 136 | List allTodos = Arrays.asList("Learn Spring MVC", 137 | "Learn Spring", "Learn to Dance"); 138 | 139 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 140 | 141 | List todos = todoBusinessImpl 142 | .retrieveTodosRelatedToSpring("Ranga"); 143 | assertEquals(2, todos.size()); 144 | } 145 | 146 | @Test 147 | public void usingMockito_UsingBDD() { 148 | List allTodos = Arrays.asList("Learn Spring MVC", 149 | "Learn Spring", "Learn to Dance"); 150 | 151 | //given 152 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 153 | 154 | //when 155 | List todos = todoBusinessImpl 156 | .retrieveTodosRelatedToSpring("Ranga"); 157 | 158 | //then 159 | assertThat(todos.size(), is(2)); 160 | } 161 | 162 | @Test 163 | public void letsTestDeleteNow() { 164 | 165 | List allTodos = Arrays.asList("Learn Spring MVC", 166 | "Learn Spring", "Learn to Dance"); 167 | 168 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 169 | 170 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 171 | 172 | verify(todoService).deleteTodo("Learn to Dance"); 173 | 174 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 175 | 176 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 177 | 178 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 179 | // atLeastOnce, atLeast 180 | 181 | } 182 | 183 | @Test 184 | public void captureArgument() { 185 | List allTodos = Arrays.asList("Learn Spring MVC", 186 | "Learn Spring", "Learn to Dance"); 187 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 188 | 189 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 190 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 191 | 192 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 193 | } 194 | } 195 | ``` 196 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoRulesTest.java 197 | ``` 198 | package com.in28minutes.business; 199 | 200 | import static org.hamcrest.CoreMatchers.is; 201 | import static org.junit.Assert.assertEquals; 202 | import static org.junit.Assert.assertThat; 203 | import static org.mockito.BDDMockito.given; 204 | import static org.mockito.Mockito.verify; 205 | import static org.mockito.Mockito.when; 206 | 207 | import java.util.Arrays; 208 | import java.util.List; 209 | 210 | import org.junit.Rule; 211 | import org.junit.Test; 212 | import org.mockito.ArgumentCaptor; 213 | import org.mockito.Captor; 214 | import org.mockito.InjectMocks; 215 | import org.mockito.Mock; 216 | import org.mockito.Mockito; 217 | import org.mockito.junit.MockitoJUnit; 218 | import org.mockito.junit.MockitoRule; 219 | 220 | import com.in28minutes.data.api.TodoService; 221 | 222 | public class TodoBusinessImplMockitoRulesTest { 223 | 224 | @Rule 225 | public MockitoRule mockitoRule = MockitoJUnit.rule(); 226 | 227 | @Mock 228 | TodoService todoService; 229 | 230 | @InjectMocks 231 | TodoBusinessImpl todoBusinessImpl; 232 | 233 | @Captor 234 | ArgumentCaptor stringArgumentCaptor; 235 | 236 | @Test 237 | public void usingMockito() { 238 | List allTodos = Arrays.asList("Learn Spring MVC", 239 | "Learn Spring", "Learn to Dance"); 240 | 241 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 242 | 243 | List todos = todoBusinessImpl 244 | .retrieveTodosRelatedToSpring("Ranga"); 245 | assertEquals(2, todos.size()); 246 | } 247 | 248 | @Test 249 | public void usingMockito_UsingBDD() { 250 | List allTodos = Arrays.asList("Learn Spring MVC", 251 | "Learn Spring", "Learn to Dance"); 252 | 253 | //given 254 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 255 | 256 | //when 257 | List todos = todoBusinessImpl 258 | .retrieveTodosRelatedToSpring("Ranga"); 259 | 260 | //then 261 | assertThat(todos.size(), is(2)); 262 | } 263 | 264 | @Test 265 | public void letsTestDeleteNow() { 266 | 267 | List allTodos = Arrays.asList("Learn Spring MVC", 268 | "Learn Spring", "Learn to Dance"); 269 | 270 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 271 | 272 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 273 | 274 | verify(todoService).deleteTodo("Learn to Dance"); 275 | 276 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 277 | 278 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 279 | 280 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 281 | // atLeastOnce, atLeast 282 | 283 | } 284 | 285 | @Test 286 | public void captureArgument() { 287 | List allTodos = Arrays.asList("Learn Spring MVC", 288 | "Learn Spring", "Learn to Dance"); 289 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 290 | 291 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 292 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 293 | 294 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 295 | } 296 | } 297 | ``` 298 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 299 | ``` 300 | package com.in28minutes.business; 301 | 302 | import static org.hamcrest.CoreMatchers.is; 303 | import static org.junit.Assert.assertEquals; 304 | import static org.junit.Assert.assertThat; 305 | import static org.mockito.BDDMockito.given; 306 | import static org.mockito.Mockito.mock; 307 | import static org.mockito.Mockito.verify; 308 | import static org.mockito.Mockito.when; 309 | 310 | import java.util.Arrays; 311 | import java.util.List; 312 | 313 | import org.junit.Test; 314 | import org.mockito.ArgumentCaptor; 315 | import org.mockito.Mockito; 316 | 317 | import com.in28minutes.data.api.TodoService; 318 | 319 | public class TodoBusinessImplMockitoTest { 320 | 321 | @Test 322 | public void usingMockito() { 323 | TodoService todoService = mock(TodoService.class); 324 | List allTodos = Arrays.asList("Learn Spring MVC", 325 | "Learn Spring", "Learn to Dance"); 326 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 327 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 328 | List todos = todoBusinessImpl 329 | .retrieveTodosRelatedToSpring("Ranga"); 330 | assertEquals(2, todos.size()); 331 | } 332 | 333 | @Test 334 | public void usingMockito_UsingBDD() { 335 | TodoService todoService = mock(TodoService.class); 336 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 337 | List allTodos = Arrays.asList("Learn Spring MVC", 338 | "Learn Spring", "Learn to Dance"); 339 | 340 | //given 341 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 342 | 343 | //when 344 | List todos = todoBusinessImpl 345 | .retrieveTodosRelatedToSpring("Ranga"); 346 | 347 | //then 348 | assertThat(todos.size(), is(2)); 349 | } 350 | 351 | @Test 352 | public void letsTestDeleteNow() { 353 | 354 | TodoService todoService = mock(TodoService.class); 355 | 356 | List allTodos = Arrays.asList("Learn Spring MVC", 357 | "Learn Spring", "Learn to Dance"); 358 | 359 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 360 | 361 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 362 | 363 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 364 | 365 | verify(todoService).deleteTodo("Learn to Dance"); 366 | 367 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 368 | 369 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 370 | 371 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 372 | // atLeastOnce, atLeast 373 | 374 | } 375 | 376 | @Test 377 | public void captureArgument() { 378 | ArgumentCaptor argumentCaptor = ArgumentCaptor 379 | .forClass(String.class); 380 | 381 | TodoService todoService = mock(TodoService.class); 382 | 383 | List allTodos = Arrays.asList("Learn Spring MVC", 384 | "Learn Spring", "Learn to Dance"); 385 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 386 | 387 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 388 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 389 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 390 | 391 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 392 | } 393 | } 394 | ``` 395 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 396 | ``` 397 | package com.in28minutes.business; 398 | 399 | import static org.junit.Assert.assertEquals; 400 | 401 | import java.util.List; 402 | 403 | import org.junit.Test; 404 | 405 | import com.in28minutes.data.api.TodoService; 406 | import com.in28minutes.data.stub.TodoServiceStub; 407 | 408 | public class TodoBusinessImplStubTest { 409 | 410 | @Test 411 | public void usingAStub() { 412 | TodoService todoService = new TodoServiceStub(); 413 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 414 | List todos = todoBusinessImpl 415 | .retrieveTodosRelatedToSpring("Ranga"); 416 | assertEquals(2, todos.size()); 417 | } 418 | } 419 | ``` 420 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 421 | ``` 422 | package com.in28minutes.data.stub; 423 | 424 | import java.util.Arrays; 425 | import java.util.List; 426 | 427 | import com.in28minutes.data.api.TodoService; 428 | 429 | public class TodoServiceStub implements TodoService { 430 | public List retrieveTodos(String user) { 431 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 432 | "Learn to Dance"); 433 | } 434 | 435 | public void deleteTodo(String todo) { 436 | 437 | } 438 | } 439 | ``` 440 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 441 | ``` 442 | package com.in28minutes.mockito; 443 | 444 | import static org.junit.Assert.assertTrue; 445 | 446 | import org.junit.Test; 447 | 448 | public class FirstMockitoTest { 449 | 450 | @Test 451 | public void test() { 452 | assertTrue(true); 453 | } 454 | 455 | } 456 | ``` 457 | ### /src/test/java/com/in28minutes/mockito/HamcrestMatcherTest.java 458 | ``` 459 | package com.in28minutes.mockito; 460 | 461 | import static org.hamcrest.CoreMatchers.hasItems; 462 | import static org.hamcrest.MatcherAssert.assertThat; 463 | import static org.hamcrest.Matchers.arrayContainingInAnyOrder; 464 | import static org.hamcrest.Matchers.arrayWithSize; 465 | import static org.hamcrest.Matchers.greaterThan; 466 | import static org.hamcrest.Matchers.hasSize; 467 | import static org.hamcrest.Matchers.isEmptyOrNullString; 468 | import static org.hamcrest.Matchers.isEmptyString; 469 | import static org.hamcrest.Matchers.lessThan; 470 | import static org.hamcrest.core.Every.everyItem; 471 | 472 | import java.util.Arrays; 473 | import java.util.List; 474 | 475 | import org.junit.Test; 476 | 477 | public class HamcrestMatcherTest { 478 | 479 | @Test 480 | public void basicHamcrestMatchers() { 481 | List scores = Arrays.asList(99, 100, 101, 105); 482 | assertThat(scores, hasSize(4)); 483 | assertThat(scores, hasItems(100, 101)); 484 | assertThat(scores, everyItem(greaterThan(90))); 485 | assertThat(scores, everyItem(lessThan(200))); 486 | 487 | // String 488 | assertThat("", isEmptyString()); 489 | assertThat(null, isEmptyOrNullString()); 490 | 491 | // Array 492 | Integer[] marks = { 1, 2, 3 }; 493 | 494 | assertThat(marks, arrayWithSize(3)); 495 | assertThat(marks, arrayContainingInAnyOrder(2, 3, 1)); 496 | 497 | } 498 | } 499 | ``` 500 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 501 | ``` 502 | package com.in28minutes.mockito; 503 | 504 | import static org.hamcrest.CoreMatchers.is; 505 | import static org.junit.Assert.assertEquals; 506 | import static org.junit.Assert.assertNull; 507 | import static org.junit.Assert.assertThat; 508 | import static org.mockito.BDDMockito.given; 509 | import static org.mockito.Mockito.mock; 510 | import static org.mockito.Mockito.when; 511 | 512 | import java.util.List; 513 | 514 | import org.junit.Test; 515 | import org.mockito.Mockito; 516 | 517 | public class ListTest { 518 | 519 | @Test 520 | public void letsMockListSize() { 521 | List list = mock(List.class); 522 | when(list.size()).thenReturn(10); 523 | assertEquals(10, list.size()); 524 | } 525 | 526 | @Test 527 | public void letsMockListSizeWithMultipleReturnValues() { 528 | List list = mock(List.class); 529 | when(list.size()).thenReturn(10).thenReturn(20); 530 | assertEquals(10, list.size()); // First Call 531 | assertEquals(20, list.size()); // Second Call 532 | } 533 | 534 | @Test 535 | public void letsMockListGet() { 536 | List list = mock(List.class); 537 | when(list.get(0)).thenReturn("in28Minutes"); 538 | assertEquals("in28Minutes", list.get(0)); 539 | assertNull(list.get(1)); 540 | } 541 | 542 | @Test(expected = RuntimeException.class) 543 | public void letsMockListGetToThrowException() { 544 | List list = mock(List.class); 545 | when(list.get(Mockito.anyInt())).thenThrow( 546 | new RuntimeException("Something went wrong")); 547 | list.get(0); 548 | } 549 | 550 | @Test 551 | public void letsMockListGetWithAny() { 552 | List list = mock(List.class); 553 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 554 | // If you are using argument matchers, all arguments 555 | // have to be provided by matchers. 556 | assertEquals("in28Minutes", list.get(0)); 557 | assertEquals("in28Minutes", list.get(1)); 558 | } 559 | 560 | @Test 561 | public void bddAliases_UsingGivenWillReturn() { 562 | List list = mock(List.class); 563 | 564 | //given 565 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 566 | 567 | //then 568 | assertThat("in28Minutes", is(list.get(0))); 569 | assertThat("in28Minutes", is(list.get(0))); 570 | } 571 | } 572 | ``` 573 | -------------------------------------------------------------------------------- /Step12.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Real world Example with Spring. 3 | - Not very different from previous example. 4 | 5 | ## Useful Snippets and References 6 | - Download the zip mockito-real-world-example-with-spring.zip and setup this maven project 7 | - For help : use our installation guide - https://github.com/in28minutes/SpringIn28Minutes/blob/master/InstallationGuide-JavaEclipseAndMaven_v2.pdf & https://www.youtube.com/watch?v=DLPjCZ5n_SM & 8 | https://www.youtube.com/watch?v=-xFzftkdycI 9 | -------------------------------------------------------------------------------- /Step13.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Understand what a Spy does? 3 | - Creating a spy with Mockito? 4 | - Overriding specific methods in a spy? 5 | 6 | ## Files List 7 | ### /pom.xml 8 | ``` 9 | 11 | 4.0.0 12 | com.in28minutes.mockito 13 | mockito-tutorial 14 | 0.0.1-SNAPSHOT 15 | 16 | 17 | junit 18 | junit 19 | 4.12 20 | test 21 | 22 | 23 | org.mockito 24 | mockito-all 25 | 1.10.19 26 | test 27 | 28 | 29 | org.hamcrest 30 | hamcrest-library 31 | 1.3 32 | test 33 | 34 | 35 | 36 | ``` 37 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 38 | ``` 39 | package com.in28minutes.business; 40 | 41 | import java.util.ArrayList; 42 | import java.util.List; 43 | 44 | import com.in28minutes.data.api.TodoService; 45 | 46 | public class TodoBusinessImpl { 47 | 48 | private TodoService todoService; 49 | 50 | TodoBusinessImpl(TodoService todoService) { 51 | this.todoService = todoService; 52 | } 53 | 54 | public List retrieveTodosRelatedToSpring(String user) { 55 | List filteredTodos = new ArrayList(); 56 | List allTodos = todoService.retrieveTodos(user); 57 | for (String todo : allTodos) { 58 | if (todo.contains("Spring")) { 59 | filteredTodos.add(todo); 60 | } 61 | } 62 | return filteredTodos; 63 | } 64 | 65 | public void deleteTodosNotRelatedToSpring(String user) { 66 | List allTodos = todoService.retrieveTodos(user); 67 | for (String todo : allTodos) { 68 | if (!todo.contains("Spring")) { 69 | todoService.deleteTodo(todo); 70 | } 71 | } 72 | } 73 | } 74 | ``` 75 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 76 | ``` 77 | package com.in28minutes.data.api; 78 | 79 | import java.util.List; 80 | 81 | // External Service - Lets say this comes from WunderList 82 | public interface TodoService { 83 | 84 | public List retrieveTodos(String user); 85 | 86 | void deleteTodo(String todo); 87 | 88 | } 89 | ``` 90 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoInjectMocksTest.java 91 | ``` 92 | package com.in28minutes.business; 93 | 94 | import static org.hamcrest.CoreMatchers.is; 95 | import static org.junit.Assert.assertEquals; 96 | import static org.junit.Assert.assertThat; 97 | import static org.mockito.BDDMockito.given; 98 | import static org.mockito.Mockito.verify; 99 | import static org.mockito.Mockito.when; 100 | 101 | import java.util.Arrays; 102 | import java.util.List; 103 | 104 | import org.junit.Test; 105 | import org.junit.runner.RunWith; 106 | import org.mockito.ArgumentCaptor; 107 | import org.mockito.Captor; 108 | import org.mockito.InjectMocks; 109 | import org.mockito.Mock; 110 | import org.mockito.Mockito; 111 | import org.mockito.runners.MockitoJUnitRunner; 112 | 113 | import com.in28minutes.data.api.TodoService; 114 | 115 | @RunWith(MockitoJUnitRunner.class) 116 | public class TodoBusinessImplMockitoInjectMocksTest { 117 | @Mock 118 | TodoService todoService; 119 | 120 | @InjectMocks 121 | TodoBusinessImpl todoBusinessImpl; 122 | 123 | @Captor 124 | ArgumentCaptor stringArgumentCaptor; 125 | 126 | @Test 127 | public void usingMockito() { 128 | List allTodos = Arrays.asList("Learn Spring MVC", 129 | "Learn Spring", "Learn to Dance"); 130 | 131 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 132 | 133 | List todos = todoBusinessImpl 134 | .retrieveTodosRelatedToSpring("Ranga"); 135 | assertEquals(2, todos.size()); 136 | } 137 | 138 | @Test 139 | public void usingMockito_UsingBDD() { 140 | List allTodos = Arrays.asList("Learn Spring MVC", 141 | "Learn Spring", "Learn to Dance"); 142 | 143 | //given 144 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 145 | 146 | //when 147 | List todos = todoBusinessImpl 148 | .retrieveTodosRelatedToSpring("Ranga"); 149 | 150 | //then 151 | assertThat(todos.size(), is(2)); 152 | } 153 | 154 | @Test 155 | public void letsTestDeleteNow() { 156 | 157 | List allTodos = Arrays.asList("Learn Spring MVC", 158 | "Learn Spring", "Learn to Dance"); 159 | 160 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 161 | 162 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 163 | 164 | verify(todoService).deleteTodo("Learn to Dance"); 165 | 166 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 167 | 168 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 169 | 170 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 171 | // atLeastOnce, atLeast 172 | 173 | } 174 | 175 | @Test 176 | public void captureArgument() { 177 | List allTodos = Arrays.asList("Learn Spring MVC", 178 | "Learn Spring", "Learn to Dance"); 179 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 180 | 181 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 182 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 183 | 184 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 185 | } 186 | } 187 | ``` 188 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoRulesTest.java 189 | ``` 190 | package com.in28minutes.business; 191 | 192 | import static org.hamcrest.CoreMatchers.is; 193 | import static org.junit.Assert.assertEquals; 194 | import static org.junit.Assert.assertThat; 195 | import static org.mockito.BDDMockito.given; 196 | import static org.mockito.Mockito.verify; 197 | import static org.mockito.Mockito.when; 198 | 199 | import java.util.Arrays; 200 | import java.util.List; 201 | 202 | import org.junit.Rule; 203 | import org.junit.Test; 204 | import org.mockito.ArgumentCaptor; 205 | import org.mockito.Captor; 206 | import org.mockito.InjectMocks; 207 | import org.mockito.Mock; 208 | import org.mockito.Mockito; 209 | import org.mockito.junit.MockitoJUnit; 210 | import org.mockito.junit.MockitoRule; 211 | 212 | import com.in28minutes.data.api.TodoService; 213 | 214 | public class TodoBusinessImplMockitoRulesTest { 215 | 216 | @Rule 217 | public MockitoRule mockitoRule = MockitoJUnit.rule(); 218 | 219 | @Mock 220 | TodoService todoService; 221 | 222 | @InjectMocks 223 | TodoBusinessImpl todoBusinessImpl; 224 | 225 | @Captor 226 | ArgumentCaptor stringArgumentCaptor; 227 | 228 | @Test 229 | public void usingMockito() { 230 | List allTodos = Arrays.asList("Learn Spring MVC", 231 | "Learn Spring", "Learn to Dance"); 232 | 233 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 234 | 235 | List todos = todoBusinessImpl 236 | .retrieveTodosRelatedToSpring("Ranga"); 237 | assertEquals(2, todos.size()); 238 | } 239 | 240 | @Test 241 | public void usingMockito_UsingBDD() { 242 | List allTodos = Arrays.asList("Learn Spring MVC", 243 | "Learn Spring", "Learn to Dance"); 244 | 245 | //given 246 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 247 | 248 | //when 249 | List todos = todoBusinessImpl 250 | .retrieveTodosRelatedToSpring("Ranga"); 251 | 252 | //then 253 | assertThat(todos.size(), is(2)); 254 | } 255 | 256 | @Test 257 | public void letsTestDeleteNow() { 258 | 259 | List allTodos = Arrays.asList("Learn Spring MVC", 260 | "Learn Spring", "Learn to Dance"); 261 | 262 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 263 | 264 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 265 | 266 | verify(todoService).deleteTodo("Learn to Dance"); 267 | 268 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 269 | 270 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 271 | 272 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 273 | // atLeastOnce, atLeast 274 | 275 | } 276 | 277 | @Test 278 | public void captureArgument() { 279 | List allTodos = Arrays.asList("Learn Spring MVC", 280 | "Learn Spring", "Learn to Dance"); 281 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 282 | 283 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 284 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 285 | 286 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 287 | } 288 | } 289 | ``` 290 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 291 | ``` 292 | package com.in28minutes.business; 293 | 294 | import static org.hamcrest.CoreMatchers.is; 295 | import static org.junit.Assert.assertEquals; 296 | import static org.junit.Assert.assertThat; 297 | import static org.mockito.BDDMockito.given; 298 | import static org.mockito.Mockito.mock; 299 | import static org.mockito.Mockito.verify; 300 | import static org.mockito.Mockito.when; 301 | 302 | import java.util.Arrays; 303 | import java.util.List; 304 | 305 | import org.junit.Test; 306 | import org.mockito.ArgumentCaptor; 307 | import org.mockito.Mockito; 308 | 309 | import com.in28minutes.data.api.TodoService; 310 | 311 | public class TodoBusinessImplMockitoTest { 312 | 313 | @Test 314 | public void usingMockito() { 315 | TodoService todoService = mock(TodoService.class); 316 | List allTodos = Arrays.asList("Learn Spring MVC", 317 | "Learn Spring", "Learn to Dance"); 318 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 319 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 320 | List todos = todoBusinessImpl 321 | .retrieveTodosRelatedToSpring("Ranga"); 322 | assertEquals(2, todos.size()); 323 | } 324 | 325 | @Test 326 | public void usingMockito_UsingBDD() { 327 | TodoService todoService = mock(TodoService.class); 328 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 329 | List allTodos = Arrays.asList("Learn Spring MVC", 330 | "Learn Spring", "Learn to Dance"); 331 | 332 | //given 333 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 334 | 335 | //when 336 | List todos = todoBusinessImpl 337 | .retrieveTodosRelatedToSpring("Ranga"); 338 | 339 | //then 340 | assertThat(todos.size(), is(2)); 341 | } 342 | 343 | @Test 344 | public void letsTestDeleteNow() { 345 | 346 | TodoService todoService = mock(TodoService.class); 347 | 348 | List allTodos = Arrays.asList("Learn Spring MVC", 349 | "Learn Spring", "Learn to Dance"); 350 | 351 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 352 | 353 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 354 | 355 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 356 | 357 | verify(todoService).deleteTodo("Learn to Dance"); 358 | 359 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 360 | 361 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 362 | 363 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 364 | // atLeastOnce, atLeast 365 | 366 | } 367 | 368 | @Test 369 | public void captureArgument() { 370 | ArgumentCaptor argumentCaptor = ArgumentCaptor 371 | .forClass(String.class); 372 | 373 | TodoService todoService = mock(TodoService.class); 374 | 375 | List allTodos = Arrays.asList("Learn Spring MVC", 376 | "Learn Spring", "Learn to Dance"); 377 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 378 | 379 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 380 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 381 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 382 | 383 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 384 | } 385 | } 386 | ``` 387 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 388 | ``` 389 | package com.in28minutes.business; 390 | 391 | import static org.junit.Assert.assertEquals; 392 | 393 | import java.util.List; 394 | 395 | import org.junit.Test; 396 | 397 | import com.in28minutes.data.api.TodoService; 398 | import com.in28minutes.data.stub.TodoServiceStub; 399 | 400 | public class TodoBusinessImplStubTest { 401 | 402 | @Test 403 | public void usingAStub() { 404 | TodoService todoService = new TodoServiceStub(); 405 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 406 | List todos = todoBusinessImpl 407 | .retrieveTodosRelatedToSpring("Ranga"); 408 | assertEquals(2, todos.size()); 409 | } 410 | } 411 | ``` 412 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 413 | ``` 414 | package com.in28minutes.data.stub; 415 | 416 | import java.util.Arrays; 417 | import java.util.List; 418 | 419 | import com.in28minutes.data.api.TodoService; 420 | 421 | public class TodoServiceStub implements TodoService { 422 | public List retrieveTodos(String user) { 423 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 424 | "Learn to Dance"); 425 | } 426 | 427 | public void deleteTodo(String todo) { 428 | 429 | } 430 | } 431 | ``` 432 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 433 | ``` 434 | package com.in28minutes.mockito; 435 | 436 | import static org.junit.Assert.assertTrue; 437 | 438 | import org.junit.Test; 439 | 440 | public class FirstMockitoTest { 441 | 442 | @Test 443 | public void test() { 444 | assertTrue(true); 445 | } 446 | 447 | } 448 | ``` 449 | ### /src/test/java/com/in28minutes/mockito/HamcrestMatcherTest.java 450 | ``` 451 | package com.in28minutes.mockito; 452 | 453 | import static org.hamcrest.CoreMatchers.hasItems; 454 | import static org.hamcrest.MatcherAssert.assertThat; 455 | import static org.hamcrest.Matchers.arrayContainingInAnyOrder; 456 | import static org.hamcrest.Matchers.arrayWithSize; 457 | import static org.hamcrest.Matchers.greaterThan; 458 | import static org.hamcrest.Matchers.hasSize; 459 | import static org.hamcrest.Matchers.isEmptyOrNullString; 460 | import static org.hamcrest.Matchers.isEmptyString; 461 | import static org.hamcrest.Matchers.lessThan; 462 | import static org.hamcrest.core.Every.everyItem; 463 | 464 | import java.util.Arrays; 465 | import java.util.List; 466 | 467 | import org.junit.Test; 468 | 469 | public class HamcrestMatcherTest { 470 | 471 | @Test 472 | public void basicHamcrestMatchers() { 473 | List scores = Arrays.asList(99, 100, 101, 105); 474 | assertThat(scores, hasSize(4)); 475 | assertThat(scores, hasItems(100, 101)); 476 | assertThat(scores, everyItem(greaterThan(90))); 477 | assertThat(scores, everyItem(lessThan(200))); 478 | 479 | // String 480 | assertThat("", isEmptyString()); 481 | assertThat(null, isEmptyOrNullString()); 482 | 483 | // Array 484 | Integer[] marks = { 1, 2, 3 }; 485 | 486 | assertThat(marks, arrayWithSize(3)); 487 | assertThat(marks, arrayContainingInAnyOrder(2, 3, 1)); 488 | 489 | } 490 | } 491 | ``` 492 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 493 | ``` 494 | package com.in28minutes.mockito; 495 | 496 | import static org.hamcrest.CoreMatchers.is; 497 | import static org.junit.Assert.assertEquals; 498 | import static org.junit.Assert.assertNull; 499 | import static org.junit.Assert.assertThat; 500 | import static org.mockito.BDDMockito.given; 501 | import static org.mockito.Mockito.mock; 502 | import static org.mockito.Mockito.when; 503 | 504 | import java.util.List; 505 | 506 | import org.junit.Test; 507 | import org.mockito.Mockito; 508 | 509 | public class ListTest { 510 | 511 | @Test 512 | public void letsMockListSize() { 513 | List list = mock(List.class); 514 | when(list.size()).thenReturn(10); 515 | assertEquals(10, list.size()); 516 | } 517 | 518 | @Test 519 | public void letsMockListSizeWithMultipleReturnValues() { 520 | List list = mock(List.class); 521 | when(list.size()).thenReturn(10).thenReturn(20); 522 | assertEquals(10, list.size()); // First Call 523 | assertEquals(20, list.size()); // Second Call 524 | } 525 | 526 | @Test 527 | public void letsMockListGet() { 528 | List list = mock(List.class); 529 | when(list.get(0)).thenReturn("in28Minutes"); 530 | assertEquals("in28Minutes", list.get(0)); 531 | assertNull(list.get(1)); 532 | } 533 | 534 | @Test(expected = RuntimeException.class) 535 | public void letsMockListGetToThrowException() { 536 | List list = mock(List.class); 537 | when(list.get(Mockito.anyInt())).thenThrow( 538 | new RuntimeException("Something went wrong")); 539 | list.get(0); 540 | } 541 | 542 | @Test 543 | public void letsMockListGetWithAny() { 544 | List list = mock(List.class); 545 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 546 | // If you are using argument matchers, all arguments 547 | // have to be provided by matchers. 548 | assertEquals("in28Minutes", list.get(0)); 549 | assertEquals("in28Minutes", list.get(1)); 550 | } 551 | 552 | @Test 553 | public void bddAliases_UsingGivenWillReturn() { 554 | List list = mock(List.class); 555 | 556 | //given 557 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 558 | 559 | //then 560 | assertThat("in28Minutes", is(list.get(0))); 561 | assertThat("in28Minutes", is(list.get(0))); 562 | } 563 | } 564 | ``` 565 | ### /src/test/java/com/in28minutes/mockito/SpyTest.java 566 | ``` 567 | package com.in28minutes.mockito; 568 | 569 | import static org.junit.Assert.assertEquals; 570 | import static org.mockito.Mockito.spy; 571 | import static org.mockito.Mockito.stub; 572 | import static org.mockito.Mockito.verify; 573 | 574 | import java.util.ArrayList; 575 | import java.util.List; 576 | 577 | import org.junit.Test; 578 | 579 | public class SpyTest { 580 | 581 | @Test 582 | public void creatingASpyOnArrayList() { 583 | List listSpy = spy(ArrayList.class); 584 | listSpy.add("Ranga"); 585 | listSpy.add("in28Minutes"); 586 | 587 | verify(listSpy).add("Ranga"); 588 | verify(listSpy).add("in28Minutes"); 589 | 590 | assertEquals(2, listSpy.size()); 591 | assertEquals("Ranga", listSpy.get(0)); 592 | } 593 | 594 | @Test 595 | public void creatingASpyOnArrayList_overridingSpecificMethods() { 596 | List listSpy = spy(ArrayList.class); 597 | listSpy.add("Ranga"); 598 | listSpy.add("in28Minutes"); 599 | 600 | stub(listSpy.size()).toReturn(-1); 601 | 602 | assertEquals(-1, listSpy.size()); 603 | assertEquals("Ranga", listSpy.get(0)); 604 | 605 | // @Spy Annotation 606 | } 607 | 608 | } 609 | ``` 610 | -------------------------------------------------------------------------------- /Step14.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Some Theory : Why does Mockito not allow stubbing final and private methods? 3 | 4 | ## Useful Snippets and References 5 | - [https://github.com/mockito/mockito/wiki/Mockito-And-Private-Methods](https://github.com/mockito/mockito/wiki/Mockito-And-Private-Methods) 6 | - [https://github.com/mockito/mockito/wiki/FAQ](https://github.com/mockito/mockito/wiki/FAQ) 7 | -------------------------------------------------------------------------------- /Step15.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Add dependency on PowerMock. 3 | - Using PowerMock and Mockito to mock a Static Method. 4 | - PowerMockitoMockingStaticMethodTest 5 | 6 | ## Useful Snippets and References 7 | pom.xml 8 | ``` 9 | 10 | org.powermock 11 | powermock-api-mockito 12 | 1.6.4 13 | test 14 | 15 | 16 | org.powermock 17 | powermock-module-junit4 18 | 1.6.4 19 | test 20 | 21 | 22 | ``` 23 | Other Useful Snippets 24 | ``` 25 | @RunWith(PowerMockRunner.class) 26 | @PrepareForTest({ UtilityClass.class}) 27 | 28 | PowerMockito.mockStatic(UtilityClass.class); 29 | when(UtilityClass.staticMethod(anyLong())).thenReturn(150); 30 | 31 | PowerMockito.verifyStatic(); 32 | UtilityClass.staticMethod(1 + 2 + 3); 33 | ``` 34 | ## Files List 35 | ## Files List 36 | ### /pom.xml 37 | ``` 38 | 40 | 4.0.0 41 | com.in28minutes.mockito 42 | mockito-tutorial 43 | 0.0.1-SNAPSHOT 44 | 45 | 46 | junit 47 | junit 48 | 4.12 49 | test 50 | 51 | 52 | org.mockito 53 | mockito-all 54 | 1.10.19 55 | test 56 | 57 | 58 | org.hamcrest 59 | hamcrest-library 60 | 1.3 61 | test 62 | 63 | 64 | org.powermock 65 | powermock-api-mockito 66 | 1.6.4 67 | test 68 | 69 | 70 | org.powermock 71 | powermock-module-junit4 72 | 1.6.4 73 | test 74 | 75 | 76 | 77 | 78 | 79 | org.apache.maven.plugins 80 | maven-compiler-plugin 81 | 82 | 1.8 83 | 1.8 84 | 85 | 86 | 87 | 88 | 89 | ``` 90 | ### /src/main/java/com/in28minutes/business/TodoBusinessImpl.java 91 | ``` 92 | package com.in28minutes.business; 93 | 94 | import java.util.ArrayList; 95 | import java.util.List; 96 | 97 | import com.in28minutes.data.api.TodoService; 98 | 99 | public class TodoBusinessImpl { 100 | 101 | private TodoService todoService; 102 | 103 | TodoBusinessImpl(TodoService todoService) { 104 | this.todoService = todoService; 105 | } 106 | 107 | public List retrieveTodosRelatedToSpring(String user) { 108 | List filteredTodos = new ArrayList(); 109 | List allTodos = todoService.retrieveTodos(user); 110 | for (String todo : allTodos) { 111 | if (todo.contains("Spring")) { 112 | filteredTodos.add(todo); 113 | } 114 | } 115 | return filteredTodos; 116 | } 117 | 118 | public void deleteTodosNotRelatedToSpring(String user) { 119 | List allTodos = todoService.retrieveTodos(user); 120 | for (String todo : allTodos) { 121 | if (!todo.contains("Spring")) { 122 | todoService.deleteTodo(todo); 123 | } 124 | } 125 | } 126 | } 127 | ``` 128 | ### /src/main/java/com/in28minutes/data/api/TodoService.java 129 | ``` 130 | package com.in28minutes.data.api; 131 | 132 | import java.util.List; 133 | 134 | // External Service - Lets say this comes from WunderList 135 | public interface TodoService { 136 | 137 | public List retrieveTodos(String user); 138 | 139 | void deleteTodo(String todo); 140 | 141 | } 142 | ``` 143 | ### /src/main/java/com/in28minutes/junit/business/ClientBO.java 144 | ``` 145 | package com.in28minutes.junit.business; 146 | 147 | import java.util.List; 148 | 149 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 150 | import com.in28minutes.junit.model.Amount; 151 | import com.in28minutes.junit.model.Product; 152 | 153 | public interface ClientBO { 154 | 155 | Amount getClientProductsSum(List products) 156 | throws DifferentCurrenciesException; 157 | 158 | } 159 | ``` 160 | ### /src/main/java/com/in28minutes/junit/business/ClientBOImpl.java 161 | ``` 162 | package com.in28minutes.junit.business; 163 | 164 | import java.math.BigDecimal; 165 | import java.util.List; 166 | 167 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 168 | import com.in28minutes.junit.model.Amount; 169 | import com.in28minutes.junit.model.AmountImpl; 170 | import com.in28minutes.junit.model.Currency; 171 | import com.in28minutes.junit.model.Product; 172 | 173 | public class ClientBOImpl implements ClientBO { 174 | 175 | public Amount getClientProductsSum(List products) 176 | throws DifferentCurrenciesException { 177 | 178 | if (products.size() == 0) 179 | return new AmountImpl(BigDecimal.ZERO, Currency.EURO); 180 | 181 | if (!isCurrencySameForAllProducts(products)) { 182 | throw new DifferentCurrenciesException(); 183 | } 184 | 185 | BigDecimal productSum = calculateProductSum(products); 186 | 187 | Currency firstProductCurrency = products.get(0).getAmount() 188 | .getCurrency(); 189 | 190 | return new AmountImpl(productSum, firstProductCurrency); 191 | } 192 | 193 | private BigDecimal calculateProductSum(List products) { 194 | BigDecimal sum = BigDecimal.ZERO; 195 | // Calculate Sum of Products 196 | for (Product product : products) { 197 | sum = sum.add(product.getAmount().getValue()); 198 | } 199 | return sum; 200 | } 201 | 202 | private boolean isCurrencySameForAllProducts(List products) 203 | throws DifferentCurrenciesException { 204 | 205 | Currency firstProductCurrency = products.get(0).getAmount() 206 | .getCurrency(); 207 | 208 | for (Product product : products) { 209 | boolean currencySameAsFirstProduct = product.getAmount() 210 | .getCurrency().equals(firstProductCurrency); 211 | if (!currencySameAsFirstProduct) { 212 | return false; 213 | } 214 | } 215 | 216 | return true; 217 | } 218 | } 219 | ``` 220 | ### /src/main/java/com/in28minutes/junit/business/exception/DifferentCurrenciesException.java 221 | ``` 222 | package com.in28minutes.junit.business.exception; 223 | 224 | public class DifferentCurrenciesException extends Exception { 225 | 226 | /** 227 | * 228 | */ 229 | private static final long serialVersionUID = 1L; 230 | 231 | } 232 | ``` 233 | ### /src/main/java/com/in28minutes/junit/helper/StringHelper.java 234 | ``` 235 | package com.in28minutes.junit.helper; 236 | 237 | public class StringHelper { 238 | 239 | public String truncateAInFirst2Positions(String str) { 240 | if (str.length() <= 2) 241 | return str.replaceAll("A", ""); 242 | 243 | String first2Chars = str.substring(0, 2); 244 | String stringMinusFirst2Chars = str.substring(2); 245 | 246 | return first2Chars.replaceAll("A", "") + stringMinusFirst2Chars; 247 | } 248 | 249 | public boolean areFirstAndLastTwoCharactersTheSame(String str) { 250 | 251 | if (str.length() <= 1) 252 | return false; 253 | if (str.length() == 2) 254 | return true; 255 | 256 | String first2Chars = str.substring(0, 2); 257 | 258 | String last2Chars = str.substring(str.length() - 2); 259 | 260 | return first2Chars.equals(last2Chars); 261 | } 262 | 263 | } 264 | ``` 265 | ### /src/main/java/com/in28minutes/junit/model/Amount.java 266 | ``` 267 | package com.in28minutes.junit.model; 268 | 269 | import java.math.BigDecimal; 270 | 271 | public interface Amount { 272 | BigDecimal getValue(); 273 | 274 | Currency getCurrency(); 275 | } 276 | ``` 277 | ### /src/main/java/com/in28minutes/junit/model/AmountImpl.java 278 | ``` 279 | package com.in28minutes.junit.model; 280 | 281 | import java.math.BigDecimal; 282 | 283 | public class AmountImpl implements Amount { 284 | 285 | BigDecimal value; 286 | Currency currency; 287 | 288 | public AmountImpl(BigDecimal value, Currency currency) { 289 | super(); 290 | this.value = value; 291 | this.currency = currency; 292 | } 293 | 294 | public void setValue(BigDecimal value) { 295 | this.value = value; 296 | } 297 | 298 | @Override 299 | public BigDecimal getValue() { 300 | return value; 301 | } 302 | 303 | public void setCurrency(Currency currency) { 304 | this.currency = currency; 305 | } 306 | 307 | @Override 308 | public Currency getCurrency() { 309 | return currency; 310 | } 311 | 312 | } 313 | ``` 314 | ### /src/main/java/com/in28minutes/junit/model/Client.java 315 | ``` 316 | package com.in28minutes.junit.model; 317 | 318 | import java.math.BigDecimal; 319 | import java.util.List; 320 | 321 | /** 322 | * Client Model API. 323 | */ 324 | public interface Client { 325 | 326 | long getId(); 327 | 328 | String getName(); 329 | 330 | Enum getType(); 331 | 332 | List getCollaterals(); 333 | 334 | List getProducts(); 335 | 336 | void setProductAmount(BigDecimal productAmount); 337 | 338 | BigDecimal getProductAmount(); 339 | 340 | } 341 | ``` 342 | ### /src/main/java/com/in28minutes/junit/model/ClientImpl.java 343 | ``` 344 | package com.in28minutes.junit.model; 345 | 346 | import java.math.BigDecimal; 347 | import java.util.List; 348 | 349 | /** 350 | * Client Model API. 351 | */ 352 | public class ClientImpl implements Client { 353 | 354 | private long id; 355 | 356 | private String name; 357 | 358 | private ClientType type; 359 | 360 | private List collaterals; 361 | 362 | private List products; 363 | 364 | private BigDecimal productAmount; 365 | 366 | public ClientImpl(long id, String name, ClientType type, 367 | List collaterals, List products) { 368 | super(); 369 | this.id = id; 370 | this.name = name; 371 | this.type = type; 372 | this.collaterals = collaterals; 373 | this.products = products; 374 | } 375 | 376 | public long getId() { 377 | return id; 378 | } 379 | 380 | public void setId(long id) { 381 | this.id = id; 382 | } 383 | 384 | @Override 385 | public String getName() { 386 | return name; 387 | } 388 | 389 | public void setName(String name) { 390 | this.name = name; 391 | } 392 | 393 | @Override 394 | public ClientType getType() { 395 | return type; 396 | } 397 | 398 | public void setType(ClientType type) { 399 | this.type = type; 400 | } 401 | 402 | @Override 403 | public List getCollaterals() { 404 | return collaterals; 405 | } 406 | 407 | public void setCollaterals(List collaterals) { 408 | this.collaterals = collaterals; 409 | } 410 | 411 | @Override 412 | public List getProducts() { 413 | return products; 414 | } 415 | 416 | public void setProducts(List products) { 417 | this.products = products; 418 | } 419 | 420 | @Override 421 | public BigDecimal getProductAmount() { 422 | return productAmount; 423 | } 424 | 425 | @Override 426 | public void setProductAmount(BigDecimal productAmount) { 427 | this.productAmount = productAmount; 428 | } 429 | 430 | } 431 | ``` 432 | ### /src/main/java/com/in28minutes/junit/model/ClientType.java 433 | ``` 434 | package com.in28minutes.junit.model; 435 | 436 | import java.util.Arrays; 437 | import java.util.List; 438 | 439 | /** 440 | * Available types of customers 441 | */ 442 | public enum ClientType { 443 | /** 444 | * 445 | */ 446 | PRIVATE("P"), 447 | /** 448 | * 449 | */ 450 | BUSINESS("Z"); 451 | 452 | private final String textValue; 453 | 454 | /** 455 | * List of natural person types. 456 | */ 457 | public static final List NATURAL_PERSON_TYPES = Arrays 458 | .asList(ClientType.PRIVATE.toString()); 459 | 460 | /** 461 | * List of corporate types. 462 | */ 463 | public static final List CORPORATE_TYPES = Arrays 464 | .asList(ClientType.BUSINESS.toString()); 465 | 466 | ClientType(final String textValue) { 467 | this.textValue = textValue; 468 | } 469 | 470 | @Override 471 | public String toString() { 472 | return textValue; 473 | } 474 | } 475 | ``` 476 | ### /src/main/java/com/in28minutes/junit/model/Collateral.java 477 | ``` 478 | package com.in28minutes.junit.model; 479 | 480 | /** 481 | * Collateral Model API. 482 | */ 483 | public interface Collateral { 484 | 485 | long getId(); 486 | 487 | String getName(); 488 | 489 | CollateralType getType(); 490 | } 491 | ``` 492 | ### /src/main/java/com/in28minutes/junit/model/CollateralImpl.java 493 | ``` 494 | package com.in28minutes.junit.model; 495 | 496 | /** 497 | * Collateral Model Object. 498 | */ 499 | public class CollateralImpl implements Collateral { 500 | 501 | private long id; 502 | 503 | private String name; 504 | 505 | private CollateralType type; 506 | 507 | public CollateralImpl(long id, String name, CollateralType type) { 508 | super(); 509 | this.id = id; 510 | this.name = name; 511 | this.type = type; 512 | } 513 | 514 | public long getId() { 515 | return id; 516 | } 517 | 518 | public void setId(long id) { 519 | this.id = id; 520 | } 521 | 522 | @Override 523 | public String getName() { 524 | return name; 525 | } 526 | 527 | public void setName(String name) { 528 | this.name = name; 529 | } 530 | 531 | @Override 532 | public CollateralType getType() { 533 | return type; 534 | } 535 | 536 | public void setType(CollateralType type) { 537 | this.type = type; 538 | } 539 | } 540 | ``` 541 | ### /src/main/java/com/in28minutes/junit/model/CollateralType.java 542 | ``` 543 | package com.in28minutes.junit.model; 544 | 545 | import java.util.Arrays; 546 | import java.util.List; 547 | 548 | /** 549 | * Available types of customers 550 | */ 551 | public enum CollateralType { 552 | REAL_ESTATE("REA"), BONDS("BND"), MUTUAL_FUNDS("MFD"), STOCKS("STK"); 553 | 554 | private final String textValue; 555 | 556 | /** 557 | * All collateral types classified as securities. 558 | */ 559 | public static final List SECURITIES = Arrays.asList(BONDS, 560 | MUTUAL_FUNDS, STOCKS); 561 | 562 | CollateralType(final String textValue) { 563 | this.textValue = textValue; 564 | } 565 | 566 | @Override 567 | public String toString() { 568 | return textValue; 569 | } 570 | } 571 | ``` 572 | ### /src/main/java/com/in28minutes/junit/model/Currency.java 573 | ``` 574 | package com.in28minutes.junit.model; 575 | 576 | public enum Currency { 577 | 578 | EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); 579 | 580 | private final String textValue; 581 | 582 | Currency(final String textValue) { 583 | this.textValue = textValue; 584 | } 585 | 586 | @Override 587 | public String toString() { 588 | return textValue; 589 | } 590 | } 591 | ``` 592 | ### /src/main/java/com/in28minutes/junit/model/Product.java 593 | ``` 594 | package com.in28minutes.junit.model; 595 | 596 | /** 597 | * Product Model API. 598 | */ 599 | public interface Product { 600 | 601 | long getId(); 602 | 603 | String getName(); 604 | 605 | ProductType getType(); 606 | 607 | Amount getAmount(); 608 | } 609 | ``` 610 | ### /src/main/java/com/in28minutes/junit/model/ProductImpl.java 611 | ``` 612 | package com.in28minutes.junit.model; 613 | 614 | /** 615 | * Collateral Model Object. 616 | */ 617 | public class ProductImpl implements Product { 618 | 619 | private long id; 620 | 621 | private String name; 622 | 623 | private ProductType type; 624 | 625 | private Amount amount; 626 | 627 | public ProductImpl(long id, String name, ProductType type, Amount amount) { 628 | super(); 629 | this.id = id; 630 | this.name = name; 631 | this.type = type; 632 | this.amount = amount; 633 | } 634 | 635 | @Override 636 | public long getId() { 637 | return id; 638 | } 639 | 640 | public void setId(long id) { 641 | this.id = id; 642 | } 643 | 644 | @Override 645 | public String getName() { 646 | return name; 647 | } 648 | 649 | public void setName(String name) { 650 | this.name = name; 651 | } 652 | 653 | @Override 654 | public ProductType getType() { 655 | return type; 656 | } 657 | 658 | public void setType(ProductType type) { 659 | this.type = type; 660 | } 661 | 662 | @Override 663 | public Amount getAmount() { 664 | return amount; 665 | } 666 | 667 | public void setAmount(Amount amount) { 668 | this.amount = amount; 669 | } 670 | } 671 | ``` 672 | ### /src/main/java/com/in28minutes/junit/model/ProductType.java 673 | ``` 674 | package com.in28minutes.junit.model; 675 | 676 | /** 677 | * Available types of customers 678 | */ 679 | public enum ProductType { 680 | LOAN("LN"), KREDIT("KRD"), BANK_GUARANTEE("BG"); 681 | 682 | private final String textValue; 683 | 684 | ProductType(final String textValue) { 685 | this.textValue = textValue; 686 | } 687 | 688 | @Override 689 | public String toString() { 690 | return textValue; 691 | } 692 | } 693 | ``` 694 | ### /src/main/java/com/in28minutes/powermock/SystemUnderTest.java 695 | ``` 696 | package com.in28minutes.powermock; 697 | 698 | import java.util.ArrayList; 699 | import java.util.List; 700 | 701 | interface Dependency { 702 | List retrieveAllStats(); 703 | } 704 | 705 | public class SystemUnderTest { 706 | private Dependency dependency; 707 | 708 | public int methodUsingAnArrayListConstructor() { 709 | ArrayList list = new ArrayList(); 710 | return list.size(); 711 | } 712 | 713 | public int methodCallingAStaticMethod() { 714 | //privateMethodUnderTest calls static method SomeClass.staticMethod 715 | List stats = dependency.retrieveAllStats(); 716 | long sum = 0; 717 | for (int stat : stats) 718 | sum += stat; 719 | return UtilityClass.staticMethod(sum); 720 | } 721 | 722 | private long privateMethodUnderTest() { 723 | List stats = dependency.retrieveAllStats(); 724 | long sum = 0; 725 | for (int stat : stats) 726 | sum += stat; 727 | return sum; 728 | } 729 | } 730 | ``` 731 | ### /src/main/java/com/in28minutes/powermock/UtilityClass.java 732 | ``` 733 | package com.in28minutes.powermock; 734 | 735 | public class UtilityClass { 736 | static int staticMethod(long value) { 737 | // Some complex logic is done here... 738 | throw new RuntimeException( 739 | "I dont want to be executed. I will anyway be mocked out."); 740 | } 741 | } 742 | ``` 743 | ### /src/test/java/com/clarity/business/ClientBOTest.java 744 | ``` 745 | package com.clarity.business; 746 | 747 | import static org.junit.Assert.assertEquals; 748 | import static org.junit.Assert.fail; 749 | 750 | import java.math.BigDecimal; 751 | import java.util.ArrayList; 752 | import java.util.List; 753 | 754 | import org.junit.Test; 755 | 756 | import com.in28minutes.junit.business.ClientBO; 757 | import com.in28minutes.junit.business.ClientBOImpl; 758 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 759 | import com.in28minutes.junit.model.Amount; 760 | import com.in28minutes.junit.model.AmountImpl; 761 | import com.in28minutes.junit.model.Currency; 762 | import com.in28minutes.junit.model.Product; 763 | import com.in28minutes.junit.model.ProductImpl; 764 | import com.in28minutes.junit.model.ProductType; 765 | 766 | public class ClientBOTest { 767 | 768 | private ClientBO clientBO = new ClientBOImpl(); 769 | 770 | @Test 771 | public void testClientProductSum() throws DifferentCurrenciesException { 772 | 773 | List products = new ArrayList(); 774 | 775 | products.add(new ProductImpl(100, "Product 15", 776 | ProductType.BANK_GUARANTEE, new AmountImpl( 777 | new BigDecimal("5.0"), Currency.EURO))); 778 | 779 | products.add(new ProductImpl(120, "Product 20", 780 | ProductType.BANK_GUARANTEE, new AmountImpl( 781 | new BigDecimal("6.0"), Currency.EURO))); 782 | 783 | Amount temp = clientBO.getClientProductsSum(products); 784 | 785 | assertEquals(Currency.EURO, temp.getCurrency()); 786 | assertEquals(new BigDecimal("11.0"), temp.getValue()); 787 | } 788 | 789 | @Test(expected = DifferentCurrenciesException.class) 790 | public void testClientProductSum1() throws DifferentCurrenciesException { 791 | 792 | List products = new ArrayList(); 793 | 794 | products.add(new ProductImpl(100, "Product 15", 795 | ProductType.BANK_GUARANTEE, new AmountImpl( 796 | new BigDecimal("5.0"), Currency.INDIAN_RUPEE))); 797 | 798 | products.add(new ProductImpl(120, "Product 20", 799 | ProductType.BANK_GUARANTEE, new AmountImpl( 800 | new BigDecimal("6.0"), Currency.EURO))); 801 | 802 | @SuppressWarnings("unused") 803 | Amount temp = null; 804 | 805 | temp = clientBO.getClientProductsSum(products); 806 | } 807 | 808 | @Test 809 | public void testClientProductSum2() { 810 | 811 | List products = new ArrayList(); 812 | 813 | Amount temp = null; 814 | 815 | try { 816 | temp = clientBO.getClientProductsSum(products); 817 | } catch (DifferentCurrenciesException e) { 818 | } 819 | assertEquals(Currency.EURO, temp.getCurrency()); 820 | assertEquals(BigDecimal.ZERO, temp.getValue()); 821 | } 822 | 823 | } 824 | ``` 825 | ### /src/test/java/com/clarity/business/ClientBOTestRefactored.java 826 | ``` 827 | package com.clarity.business; 828 | 829 | import static org.junit.Assert.assertEquals; 830 | 831 | import java.math.BigDecimal; 832 | import java.util.ArrayList; 833 | import java.util.List; 834 | 835 | import org.junit.Test; 836 | 837 | import com.in28minutes.junit.business.ClientBO; 838 | import com.in28minutes.junit.business.ClientBOImpl; 839 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 840 | import com.in28minutes.junit.model.Amount; 841 | import com.in28minutes.junit.model.AmountImpl; 842 | import com.in28minutes.junit.model.Currency; 843 | import com.in28minutes.junit.model.Product; 844 | import com.in28minutes.junit.model.ProductImpl; 845 | import com.in28minutes.junit.model.ProductType; 846 | 847 | public class ClientBOTestRefactored { 848 | 849 | private ClientBO clientBO = new ClientBOImpl(); 850 | 851 | @Test 852 | public void testClientProductSum_AllProductsSameCurrency() 853 | throws DifferentCurrenciesException { 854 | 855 | Amount[] amounts = { 856 | new AmountImpl(new BigDecimal("5.0"), Currency.EURO), 857 | new AmountImpl(new BigDecimal("6.0"), Currency.EURO) }; 858 | 859 | Amount expected = new AmountImpl(new BigDecimal("11.0"), Currency.EURO); 860 | 861 | List products = createProductListWithAmounts(amounts); 862 | 863 | Amount actual = clientBO.getClientProductsSum(products); 864 | 865 | assertAmount(actual, expected); 866 | } 867 | 868 | @Test(expected = DifferentCurrenciesException.class) 869 | public void testClientProductSum_DifferentCurrencies_ThrowsException() 870 | throws DifferentCurrenciesException { 871 | 872 | Amount[] amounts = { 873 | new AmountImpl(new BigDecimal("5.0"), Currency.EURO), 874 | new AmountImpl(new BigDecimal("6.0"), Currency.INDIAN_RUPEE) }; 875 | 876 | List products = createProductListWithAmounts(amounts); 877 | 878 | @SuppressWarnings("unused") 879 | Amount actual = clientBO.getClientProductsSum(products); 880 | 881 | } 882 | 883 | @Test 884 | public void testClientProductSum_NoProducts() 885 | throws DifferentCurrenciesException { 886 | 887 | Amount[] amounts = {}; 888 | Amount expected = new AmountImpl(BigDecimal.ZERO, Currency.EURO); 889 | 890 | List products = createProductListWithAmounts(amounts); 891 | 892 | Amount actual = clientBO.getClientProductsSum(products); 893 | 894 | 895 | assertAmount(actual, expected); 896 | } 897 | 898 | private void assertAmount(Amount actual, Amount expected) { 899 | assertEquals(expected.getCurrency(), actual.getCurrency()); 900 | assertEquals(expected.getValue(), actual.getValue()); 901 | } 902 | 903 | private List createProductListWithAmounts(Amount[] amounts) { 904 | List products = new ArrayList(); 905 | for (Amount amount : amounts) { 906 | products.add(new ProductImpl(100, "Product 15", 907 | ProductType.BANK_GUARANTEE, amount)); 908 | } 909 | return products; 910 | } 911 | 912 | } 913 | ``` 914 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoInjectMocksTest.java 915 | ``` 916 | package com.in28minutes.business; 917 | 918 | import static org.hamcrest.CoreMatchers.is; 919 | import static org.junit.Assert.assertEquals; 920 | import static org.junit.Assert.assertThat; 921 | import static org.mockito.BDDMockito.given; 922 | import static org.mockito.Mockito.verify; 923 | import static org.mockito.Mockito.when; 924 | 925 | import java.util.Arrays; 926 | import java.util.List; 927 | 928 | import org.junit.Test; 929 | import org.junit.runner.RunWith; 930 | import org.mockito.ArgumentCaptor; 931 | import org.mockito.Captor; 932 | import org.mockito.InjectMocks; 933 | import org.mockito.Mock; 934 | import org.mockito.Mockito; 935 | import org.mockito.runners.MockitoJUnitRunner; 936 | 937 | import com.in28minutes.data.api.TodoService; 938 | 939 | @RunWith(MockitoJUnitRunner.class) 940 | public class TodoBusinessImplMockitoInjectMocksTest { 941 | @Mock 942 | TodoService todoService; 943 | 944 | @InjectMocks 945 | TodoBusinessImpl todoBusinessImpl; 946 | 947 | @Captor 948 | ArgumentCaptor stringArgumentCaptor; 949 | 950 | @Test 951 | public void usingMockito() { 952 | List allTodos = Arrays.asList("Learn Spring MVC", 953 | "Learn Spring", "Learn to Dance"); 954 | 955 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 956 | 957 | List todos = todoBusinessImpl 958 | .retrieveTodosRelatedToSpring("Ranga"); 959 | assertEquals(2, todos.size()); 960 | } 961 | 962 | @Test 963 | public void usingMockito_UsingBDD() { 964 | List allTodos = Arrays.asList("Learn Spring MVC", 965 | "Learn Spring", "Learn to Dance"); 966 | 967 | //given 968 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 969 | 970 | //when 971 | List todos = todoBusinessImpl 972 | .retrieveTodosRelatedToSpring("Ranga"); 973 | 974 | //then 975 | assertThat(todos.size(), is(2)); 976 | } 977 | 978 | @Test 979 | public void letsTestDeleteNow() { 980 | 981 | List allTodos = Arrays.asList("Learn Spring MVC", 982 | "Learn Spring", "Learn to Dance"); 983 | 984 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 985 | 986 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 987 | 988 | verify(todoService).deleteTodo("Learn to Dance"); 989 | 990 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 991 | 992 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 993 | 994 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 995 | // atLeastOnce, atLeast 996 | 997 | } 998 | 999 | @Test 1000 | public void captureArgument() { 1001 | List allTodos = Arrays.asList("Learn Spring MVC", 1002 | "Learn Spring", "Learn to Dance"); 1003 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 1004 | 1005 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 1006 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 1007 | 1008 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 1009 | } 1010 | } 1011 | ``` 1012 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoRulesTest.java 1013 | ``` 1014 | package com.in28minutes.business; 1015 | 1016 | import static org.hamcrest.CoreMatchers.is; 1017 | import static org.junit.Assert.assertEquals; 1018 | import static org.junit.Assert.assertThat; 1019 | import static org.mockito.BDDMockito.given; 1020 | import static org.mockito.Mockito.verify; 1021 | import static org.mockito.Mockito.when; 1022 | 1023 | import java.util.Arrays; 1024 | import java.util.List; 1025 | 1026 | import org.junit.Rule; 1027 | import org.junit.Test; 1028 | import org.mockito.ArgumentCaptor; 1029 | import org.mockito.Captor; 1030 | import org.mockito.InjectMocks; 1031 | import org.mockito.Mock; 1032 | import org.mockito.Mockito; 1033 | import org.mockito.junit.MockitoJUnit; 1034 | import org.mockito.junit.MockitoRule; 1035 | 1036 | import com.in28minutes.data.api.TodoService; 1037 | 1038 | public class TodoBusinessImplMockitoRulesTest { 1039 | 1040 | @Rule 1041 | public MockitoRule mockitoRule = MockitoJUnit.rule(); 1042 | 1043 | @Mock 1044 | TodoService todoService; 1045 | 1046 | @InjectMocks 1047 | TodoBusinessImpl todoBusinessImpl; 1048 | 1049 | @Captor 1050 | ArgumentCaptor stringArgumentCaptor; 1051 | 1052 | @Test 1053 | public void usingMockito() { 1054 | List allTodos = Arrays.asList("Learn Spring MVC", 1055 | "Learn Spring", "Learn to Dance"); 1056 | 1057 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 1058 | 1059 | List todos = todoBusinessImpl 1060 | .retrieveTodosRelatedToSpring("Ranga"); 1061 | assertEquals(2, todos.size()); 1062 | } 1063 | 1064 | @Test 1065 | public void usingMockito_UsingBDD() { 1066 | List allTodos = Arrays.asList("Learn Spring MVC", 1067 | "Learn Spring", "Learn to Dance"); 1068 | 1069 | //given 1070 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 1071 | 1072 | //when 1073 | List todos = todoBusinessImpl 1074 | .retrieveTodosRelatedToSpring("Ranga"); 1075 | 1076 | //then 1077 | assertThat(todos.size(), is(2)); 1078 | } 1079 | 1080 | @Test 1081 | public void letsTestDeleteNow() { 1082 | 1083 | List allTodos = Arrays.asList("Learn Spring MVC", 1084 | "Learn Spring", "Learn to Dance"); 1085 | 1086 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 1087 | 1088 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 1089 | 1090 | verify(todoService).deleteTodo("Learn to Dance"); 1091 | 1092 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 1093 | 1094 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 1095 | 1096 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 1097 | // atLeastOnce, atLeast 1098 | 1099 | } 1100 | 1101 | @Test 1102 | public void captureArgument() { 1103 | List allTodos = Arrays.asList("Learn Spring MVC", 1104 | "Learn Spring", "Learn to Dance"); 1105 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 1106 | 1107 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 1108 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 1109 | 1110 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 1111 | } 1112 | } 1113 | ``` 1114 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java 1115 | ``` 1116 | package com.in28minutes.business; 1117 | 1118 | import static org.hamcrest.CoreMatchers.is; 1119 | import static org.junit.Assert.assertEquals; 1120 | import static org.junit.Assert.assertThat; 1121 | import static org.mockito.BDDMockito.given; 1122 | import static org.mockito.Mockito.mock; 1123 | import static org.mockito.Mockito.verify; 1124 | import static org.mockito.Mockito.when; 1125 | 1126 | import java.util.Arrays; 1127 | import java.util.List; 1128 | 1129 | import org.junit.Test; 1130 | import org.mockito.ArgumentCaptor; 1131 | import org.mockito.Mockito; 1132 | 1133 | import com.in28minutes.data.api.TodoService; 1134 | 1135 | public class TodoBusinessImplMockitoTest { 1136 | 1137 | @Test 1138 | public void usingMockito() { 1139 | TodoService todoService = mock(TodoService.class); 1140 | List allTodos = Arrays.asList("Learn Spring MVC", 1141 | "Learn Spring", "Learn to Dance"); 1142 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 1143 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 1144 | List todos = todoBusinessImpl 1145 | .retrieveTodosRelatedToSpring("Ranga"); 1146 | assertEquals(2, todos.size()); 1147 | } 1148 | 1149 | @Test 1150 | public void usingMockito_UsingBDD() { 1151 | TodoService todoService = mock(TodoService.class); 1152 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 1153 | List allTodos = Arrays.asList("Learn Spring MVC", 1154 | "Learn Spring", "Learn to Dance"); 1155 | 1156 | //given 1157 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 1158 | 1159 | //when 1160 | List todos = todoBusinessImpl 1161 | .retrieveTodosRelatedToSpring("Ranga"); 1162 | 1163 | //then 1164 | assertThat(todos.size(), is(2)); 1165 | } 1166 | 1167 | @Test 1168 | public void letsTestDeleteNow() { 1169 | 1170 | TodoService todoService = mock(TodoService.class); 1171 | 1172 | List allTodos = Arrays.asList("Learn Spring MVC", 1173 | "Learn Spring", "Learn to Dance"); 1174 | 1175 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 1176 | 1177 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 1178 | 1179 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 1180 | 1181 | verify(todoService).deleteTodo("Learn to Dance"); 1182 | 1183 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 1184 | 1185 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 1186 | 1187 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 1188 | // atLeastOnce, atLeast 1189 | 1190 | } 1191 | 1192 | @Test 1193 | public void captureArgument() { 1194 | ArgumentCaptor argumentCaptor = ArgumentCaptor 1195 | .forClass(String.class); 1196 | 1197 | TodoService todoService = mock(TodoService.class); 1198 | 1199 | List allTodos = Arrays.asList("Learn Spring MVC", 1200 | "Learn Spring", "Learn to Dance"); 1201 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 1202 | 1203 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 1204 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 1205 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 1206 | 1207 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 1208 | } 1209 | } 1210 | ``` 1211 | ### /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java 1212 | ``` 1213 | package com.in28minutes.business; 1214 | 1215 | import static org.junit.Assert.assertEquals; 1216 | 1217 | import java.util.List; 1218 | 1219 | import org.junit.Test; 1220 | 1221 | import com.in28minutes.data.api.TodoService; 1222 | import com.in28minutes.data.stub.TodoServiceStub; 1223 | 1224 | public class TodoBusinessImplStubTest { 1225 | 1226 | @Test 1227 | public void usingAStub() { 1228 | TodoService todoService = new TodoServiceStub(); 1229 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 1230 | List todos = todoBusinessImpl 1231 | .retrieveTodosRelatedToSpring("Ranga"); 1232 | assertEquals(2, todos.size()); 1233 | } 1234 | } 1235 | ``` 1236 | ### /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java 1237 | ``` 1238 | package com.in28minutes.data.stub; 1239 | 1240 | import java.util.Arrays; 1241 | import java.util.List; 1242 | 1243 | import com.in28minutes.data.api.TodoService; 1244 | 1245 | public class TodoServiceStub implements TodoService { 1246 | public List retrieveTodos(String user) { 1247 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 1248 | "Learn to Dance"); 1249 | } 1250 | 1251 | public void deleteTodo(String todo) { 1252 | 1253 | } 1254 | } 1255 | ``` 1256 | ### /src/test/java/com/in28minutes/junit/helper/ArraysCompareTest.java 1257 | ``` 1258 | package com.in28minutes.junit.helper; 1259 | 1260 | import static org.junit.Assert.*; 1261 | 1262 | import java.util.Arrays; 1263 | 1264 | import org.junit.Test; 1265 | 1266 | public class ArraysCompareTest { 1267 | 1268 | @Test 1269 | public void testArraySort_RandomArray() { 1270 | int[] numbers = { 12, 3, 4, 1 }; 1271 | int[] expected = { 1, 3, 4, 12 }; 1272 | Arrays.sort(numbers); 1273 | assertArrayEquals(expected, numbers); 1274 | } 1275 | 1276 | @Test(expected=NullPointerException.class) 1277 | public void testArraySort_NullArray() { 1278 | int[] numbers = null; 1279 | Arrays.sort(numbers); 1280 | } 1281 | 1282 | @Test(timeout=100) 1283 | public void testSort_Performance(){ 1284 | int array[] = {12,23,4}; 1285 | for(int i=1;i<=1000000;i++) 1286 | { 1287 | array[0] = i; 1288 | Arrays.sort(array); 1289 | } 1290 | } 1291 | 1292 | } 1293 | ``` 1294 | ### /src/test/java/com/in28minutes/junit/helper/ArraysTest.java 1295 | ``` 1296 | package com.in28minutes.junit.helper; 1297 | 1298 | import static org.junit.Assert.*; 1299 | 1300 | 1301 | import java.util.Arrays; 1302 | 1303 | import org.junit.Test; 1304 | 1305 | public class ArraysTest { 1306 | @Test(timeout=100) 1307 | public void testPerformance() { 1308 | for(int i=0;i<1000000;i++){ 1309 | Arrays.sort(new int[]{i,i-1,i+1}); 1310 | } 1311 | } 1312 | } 1313 | ``` 1314 | ### /src/test/java/com/in28minutes/junit/helper/QuickBeforeAfterTest.java 1315 | ``` 1316 | package com.in28minutes.junit.helper; 1317 | 1318 | import static org.junit.Assert.*; 1319 | 1320 | import org.junit.After; 1321 | import org.junit.AfterClass; 1322 | import org.junit.Before; 1323 | import org.junit.BeforeClass; 1324 | import org.junit.Test; 1325 | 1326 | public class QuickBeforeAfterTest { 1327 | 1328 | @BeforeClass 1329 | public static void beforeClass(){ 1330 | System.out.println("Before Class"); 1331 | } 1332 | 1333 | @Before 1334 | public void setup(){ 1335 | System.out.println("Before Test"); 1336 | } 1337 | 1338 | @Test 1339 | public void test1() { 1340 | System.out.println("test1 executed"); 1341 | } 1342 | 1343 | @Test 1344 | public void test2() { 1345 | System.out.println("test2 executed"); 1346 | } 1347 | 1348 | @After 1349 | public void teardown() { 1350 | System.out.println("After test"); 1351 | } 1352 | 1353 | @AfterClass 1354 | public static void afterClass(){ 1355 | System.out.println("After Class"); 1356 | } 1357 | 1358 | } 1359 | ``` 1360 | ### /src/test/java/com/in28minutes/junit/helper/StringHelperParameterizedTest.java 1361 | ``` 1362 | package com.in28minutes.junit.helper; 1363 | 1364 | import static org.junit.Assert.*; 1365 | 1366 | import java.util.Arrays; 1367 | import java.util.Collection; 1368 | 1369 | import org.junit.Before; 1370 | import org.junit.Test; 1371 | import org.junit.runner.RunWith; 1372 | import org.junit.runners.Parameterized; 1373 | import org.junit.runners.Parameterized.Parameters; 1374 | 1375 | @RunWith(Parameterized.class) 1376 | public class StringHelperParameterizedTest { 1377 | 1378 | // AACD => CD ACD => CD CDEF=>CDEF CDAA => CDAA 1379 | 1380 | StringHelper helper = new StringHelper(); 1381 | 1382 | private String input; 1383 | private String expectedOutput; 1384 | 1385 | public StringHelperParameterizedTest(String input, String expectedOutput) { 1386 | this.input = input; 1387 | this.expectedOutput = expectedOutput; 1388 | } 1389 | 1390 | @Parameters 1391 | public static Collection testConditions() { 1392 | String expectedOutputs[][] = { 1393 | { "AACD", "CD" }, 1394 | { "ACD", "CD" } }; 1395 | return Arrays.asList(expectedOutputs); 1396 | } 1397 | 1398 | @Test 1399 | public void testTruncateAInFirst2Positions() { 1400 | assertEquals(expectedOutput, 1401 | helper.truncateAInFirst2Positions(input)); 1402 | } 1403 | } 1404 | ``` 1405 | ### /src/test/java/com/in28minutes/junit/helper/StringHelperTest.java 1406 | ``` 1407 | package com.in28minutes.junit.helper; 1408 | 1409 | import static org.junit.Assert.*; 1410 | 1411 | import org.junit.Before; 1412 | import org.junit.Test; 1413 | 1414 | public class StringHelperTest { 1415 | 1416 | // AACD => CD ACD => CD CDEF=>CDEF CDAA => CDAA 1417 | 1418 | StringHelper helper; 1419 | 1420 | @Before 1421 | public void before(){ 1422 | helper = new StringHelper(); 1423 | } 1424 | 1425 | 1426 | @Test 1427 | public void testTruncateAInFirst2Positions_AinFirst2Positions() { 1428 | assertEquals("CD", helper.truncateAInFirst2Positions("AACD")); 1429 | } 1430 | 1431 | @Test 1432 | public void testTruncateAInFirst2Positions_AinFirstPosition() { 1433 | assertEquals("CD", helper.truncateAInFirst2Positions("ACD")); 1434 | } 1435 | 1436 | // ABCD => false, ABAB => true, AB => true, A => false 1437 | @Test 1438 | public void testAreFirstAndLastTwoCharactersTheSame_BasicNegativeScenario() { 1439 | assertFalse( 1440 | helper.areFirstAndLastTwoCharactersTheSame("ABCD")); 1441 | } 1442 | 1443 | @Test 1444 | public void testAreFirstAndLastTwoCharactersTheSame_BasicPositiveScenario() { 1445 | assertTrue( 1446 | helper.areFirstAndLastTwoCharactersTheSame("ABAB")); 1447 | } 1448 | 1449 | 1450 | } 1451 | ``` 1452 | ### /src/test/java/com/in28minutes/junit/suite/DummyTestSuite.java 1453 | ``` 1454 | package com.in28minutes.junit.suite; 1455 | 1456 | import org.junit.runner.RunWith; 1457 | import org.junit.runners.Suite; 1458 | import org.junit.runners.Suite.SuiteClasses; 1459 | 1460 | import com.in28minutes.junit.helper.ArraysTest; 1461 | import com.in28minutes.junit.helper.StringHelperTest; 1462 | 1463 | @RunWith(Suite.class) 1464 | @SuiteClasses({ArraysTest.class,StringHelperTest.class}) 1465 | public class DummyTestSuite { 1466 | 1467 | } 1468 | ``` 1469 | ### /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java 1470 | ``` 1471 | package com.in28minutes.mockito; 1472 | 1473 | import static org.junit.Assert.assertTrue; 1474 | 1475 | import org.junit.Test; 1476 | 1477 | public class FirstMockitoTest { 1478 | 1479 | @Test 1480 | public void test() { 1481 | assertTrue(true); 1482 | } 1483 | 1484 | } 1485 | ``` 1486 | ### /src/test/java/com/in28minutes/mockito/HamcrestMatcherTest.java 1487 | ``` 1488 | package com.in28minutes.mockito; 1489 | 1490 | import static org.hamcrest.CoreMatchers.hasItems; 1491 | import static org.hamcrest.MatcherAssert.assertThat; 1492 | import static org.hamcrest.Matchers.arrayContainingInAnyOrder; 1493 | import static org.hamcrest.Matchers.arrayWithSize; 1494 | import static org.hamcrest.Matchers.greaterThan; 1495 | import static org.hamcrest.Matchers.hasSize; 1496 | import static org.hamcrest.Matchers.isEmptyOrNullString; 1497 | import static org.hamcrest.Matchers.isEmptyString; 1498 | import static org.hamcrest.Matchers.lessThan; 1499 | import static org.hamcrest.core.Every.everyItem; 1500 | 1501 | import java.util.Arrays; 1502 | import java.util.List; 1503 | 1504 | import org.junit.Test; 1505 | 1506 | public class HamcrestMatcherTest { 1507 | 1508 | @Test 1509 | public void basicHamcrestMatchers() { 1510 | List scores = Arrays.asList(99, 100, 101, 105); 1511 | assertThat(scores, hasSize(4)); 1512 | assertThat(scores, hasItems(100, 101)); 1513 | assertThat(scores, everyItem(greaterThan(90))); 1514 | assertThat(scores, everyItem(lessThan(200))); 1515 | 1516 | // String 1517 | assertThat("", isEmptyString()); 1518 | assertThat(null, isEmptyOrNullString()); 1519 | 1520 | // Array 1521 | Integer[] marks = { 1, 2, 3 }; 1522 | 1523 | assertThat(marks, arrayWithSize(3)); 1524 | assertThat(marks, arrayContainingInAnyOrder(2, 3, 1)); 1525 | 1526 | } 1527 | } 1528 | ``` 1529 | ### /src/test/java/com/in28minutes/mockito/ListTest.java 1530 | ``` 1531 | package com.in28minutes.mockito; 1532 | 1533 | import static org.hamcrest.CoreMatchers.is; 1534 | import static org.junit.Assert.assertEquals; 1535 | import static org.junit.Assert.assertNull; 1536 | import static org.junit.Assert.assertThat; 1537 | import static org.mockito.BDDMockito.given; 1538 | import static org.mockito.Mockito.mock; 1539 | import static org.mockito.Mockito.when; 1540 | 1541 | import java.util.List; 1542 | 1543 | import org.junit.Test; 1544 | import org.mockito.Mockito; 1545 | 1546 | public class ListTest { 1547 | 1548 | @Test 1549 | public void letsMockListSize() { 1550 | List list = mock(List.class); 1551 | when(list.size()).thenReturn(10); 1552 | assertEquals(10, list.size()); 1553 | } 1554 | 1555 | @Test 1556 | public void letsMockListSizeWithMultipleReturnValues() { 1557 | List list = mock(List.class); 1558 | when(list.size()).thenReturn(10).thenReturn(20); 1559 | assertEquals(10, list.size()); // First Call 1560 | assertEquals(20, list.size()); // Second Call 1561 | } 1562 | 1563 | @Test 1564 | public void letsMockListGet() { 1565 | List list = mock(List.class); 1566 | when(list.get(0)).thenReturn("in28Minutes"); 1567 | assertEquals("in28Minutes", list.get(0)); 1568 | assertNull(list.get(1)); 1569 | } 1570 | 1571 | @Test(expected = RuntimeException.class) 1572 | public void letsMockListGetToThrowException() { 1573 | List list = mock(List.class); 1574 | when(list.get(Mockito.anyInt())).thenThrow( 1575 | new RuntimeException("Something went wrong")); 1576 | list.get(0); 1577 | } 1578 | 1579 | @Test 1580 | public void letsMockListGetWithAny() { 1581 | List list = mock(List.class); 1582 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 1583 | // If you are using argument matchers, all arguments 1584 | // have to be provided by matchers. 1585 | assertEquals("in28Minutes", list.get(0)); 1586 | assertEquals("in28Minutes", list.get(1)); 1587 | } 1588 | 1589 | @Test 1590 | public void bddAliases_UsingGivenWillReturn() { 1591 | List list = mock(List.class); 1592 | 1593 | //given 1594 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 1595 | 1596 | //then 1597 | assertThat("in28Minutes", is(list.get(0))); 1598 | assertThat("in28Minutes", is(list.get(0))); 1599 | } 1600 | } 1601 | ``` 1602 | ### /src/test/java/com/in28minutes/mockito/SpyTest.java 1603 | ``` 1604 | package com.in28minutes.mockito; 1605 | 1606 | import static org.junit.Assert.assertEquals; 1607 | import static org.mockito.Mockito.spy; 1608 | import static org.mockito.Mockito.stub; 1609 | import static org.mockito.Mockito.verify; 1610 | 1611 | import java.util.ArrayList; 1612 | import java.util.List; 1613 | 1614 | import org.junit.Test; 1615 | 1616 | public class SpyTest { 1617 | 1618 | @Test 1619 | public void creatingASpyOnArrayList() { 1620 | List listSpy = spy(ArrayList.class); 1621 | listSpy.add("Ranga"); 1622 | listSpy.add("in28Minutes"); 1623 | 1624 | verify(listSpy).add("Ranga"); 1625 | verify(listSpy).add("in28Minutes"); 1626 | 1627 | assertEquals(2, listSpy.size()); 1628 | assertEquals("Ranga", listSpy.get(0)); 1629 | } 1630 | 1631 | @Test 1632 | public void creatingASpyOnArrayList_overridingSpecificMethods() { 1633 | List listSpy = spy(ArrayList.class); 1634 | listSpy.add("Ranga"); 1635 | listSpy.add("in28Minutes"); 1636 | 1637 | stub(listSpy.size()).toReturn(-1); 1638 | 1639 | assertEquals(-1, listSpy.size()); 1640 | assertEquals("Ranga", listSpy.get(0)); 1641 | 1642 | // @Spy Annotation 1643 | } 1644 | 1645 | } 1646 | ``` 1647 | ### /src/test/java/com/in28minutes/powermock/PowerMockitoMockingStaticMethodTest.java 1648 | ``` 1649 | package com.in28minutes.powermock; 1650 | 1651 | import static org.junit.Assert.assertEquals; 1652 | import static org.mockito.Matchers.anyLong; 1653 | import static org.mockito.Mockito.when; 1654 | 1655 | import java.util.Arrays; 1656 | 1657 | import org.junit.Test; 1658 | import org.junit.runner.RunWith; 1659 | import org.mockito.InjectMocks; 1660 | import org.mockito.Mock; 1661 | import org.powermock.api.mockito.PowerMockito; 1662 | import org.powermock.core.classloader.annotations.PrepareForTest; 1663 | import org.powermock.modules.junit4.PowerMockRunner; 1664 | 1665 | @RunWith(PowerMockRunner.class) 1666 | @PrepareForTest({ UtilityClass.class}) 1667 | public class PowerMockitoMockingStaticMethodTest { 1668 | 1669 | @Mock 1670 | Dependency dependencyMock; 1671 | 1672 | @InjectMocks 1673 | SystemUnderTest systemUnderTest; 1674 | 1675 | @Test 1676 | public void powerMockito_MockingAStaticMethodCall() { 1677 | 1678 | when(dependencyMock.retrieveAllStats()).thenReturn( 1679 | Arrays.asList(1, 2, 3)); 1680 | 1681 | PowerMockito.mockStatic(UtilityClass.class); 1682 | 1683 | when(UtilityClass.staticMethod(anyLong())).thenReturn(150); 1684 | 1685 | assertEquals(150, systemUnderTest.methodCallingAStaticMethod()); 1686 | 1687 | //To verify a specific method call 1688 | //First : Call PowerMockito.verifyStatic() 1689 | //Second : Call the method to be verified 1690 | PowerMockito.verifyStatic(); 1691 | UtilityClass.staticMethod(1 + 2 + 3); 1692 | 1693 | // verify exact number of calls 1694 | //PowerMockito.verifyStatic(Mockito.times(1)); 1695 | 1696 | } 1697 | } 1698 | ``` 1699 | -------------------------------------------------------------------------------- /Step18.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - Good Unit Tests 3 | -- Basics 4 | --- Readable 5 | --- Fails only when there are real logic failures 6 | 7 | ## Exercises and References 8 | - FIRST. [https://pragprog.com/magazines/2012-01/unit-tests-are-first](https://pragprog.com/magazines/2012-01/unit-tests-are-first) 9 | - Patterns - [http://xunitpatterns.com](http://xunitpatterns.com) 10 | - [https://github.com/mockito/mockito/wiki/How-to-write-good-tests](https://github.com/mockito/mockito/wiki/How-to-write-good-tests) 11 | -------------------------------------------------------------------------------- /StepReference.md: -------------------------------------------------------------------------------- 1 | ## What You Will Learn during this Step: 2 | - First 3 | - Second 4 | - Third 5 | 6 | ## Useful Snippets and References 7 | First Snippet 8 | ``` 9 | ``` 10 | Second Snippet 11 | ``` 12 | ``` 13 | 14 | ## Exercises 15 | 16 | ## Files List 17 | -------------------------------------------------------------------------------- /mockito-real-world-example-with-spring.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/in28minutes/MockitoTutorialForBeginners/04ad1f28cfc7f672b1d697249dfaa074b2efdd88/mockito-real-world-example-with-spring.zip -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.in28minutes.mockito 5 | mockito-tutorial 6 | 0.0.1-SNAPSHOT 7 | 8 | 9 | junit 10 | junit 11 | 4.12 12 | test 13 | 14 | 15 | org.mockito 16 | mockito-all 17 | 1.10.19 18 | test 19 | 20 | 21 | org.hamcrest 22 | hamcrest-library 23 | 1.3 24 | test 25 | 26 | 27 | org.powermock 28 | powermock-api-mockito 29 | 1.6.4 30 | test 31 | 32 | 33 | org.powermock 34 | powermock-module-junit4 35 | 1.6.4 36 | test 37 | 38 | 39 | 40 | 41 | 42 | org.apache.maven.plugins 43 | maven-compiler-plugin 44 | 45 | 1.8 46 | 1.8 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/business/TodoBusinessImpl.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.business; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import com.in28minutes.data.api.TodoService; 7 | 8 | public class TodoBusinessImpl { 9 | 10 | private TodoService todoService; 11 | 12 | TodoBusinessImpl(TodoService todoService) { 13 | this.todoService = todoService; 14 | } 15 | 16 | public List retrieveTodosRelatedToSpring(String user) { 17 | List filteredTodos = new ArrayList(); 18 | List allTodos = todoService.retrieveTodos(user); 19 | for (String todo : allTodos) { 20 | if (todo.contains("Spring")) { 21 | filteredTodos.add(todo); 22 | } 23 | } 24 | return filteredTodos; 25 | } 26 | 27 | public void deleteTodosNotRelatedToSpring(String user) { 28 | List allTodos = todoService.retrieveTodos(user); 29 | for (String todo : allTodos) { 30 | if (!todo.contains("Spring")) { 31 | todoService.deleteTodo(todo); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/data/api/TodoService.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.data.api; 2 | 3 | import java.util.List; 4 | 5 | // External Service - Lets say this comes from WunderList 6 | public interface TodoService { 7 | 8 | public List retrieveTodos(String user); 9 | 10 | void deleteTodo(String todo); 11 | 12 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/business/ClientBO.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.business; 2 | 3 | import java.util.List; 4 | 5 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 6 | import com.in28minutes.junit.model.Amount; 7 | import com.in28minutes.junit.model.Product; 8 | 9 | public interface ClientBO { 10 | 11 | Amount getClientProductsSum(List products) 12 | throws DifferentCurrenciesException; 13 | 14 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/business/ClientBOImpl.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.business; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.List; 5 | 6 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 7 | import com.in28minutes.junit.model.Amount; 8 | import com.in28minutes.junit.model.AmountImpl; 9 | import com.in28minutes.junit.model.Currency; 10 | import com.in28minutes.junit.model.Product; 11 | 12 | public class ClientBOImpl implements ClientBO { 13 | 14 | public Amount getClientProductsSum(List products) 15 | throws DifferentCurrenciesException { 16 | 17 | if (products.size() == 0) 18 | return new AmountImpl(BigDecimal.ZERO, Currency.EURO); 19 | 20 | if (!isCurrencySameForAllProducts(products)) { 21 | throw new DifferentCurrenciesException(); 22 | } 23 | 24 | BigDecimal productSum = calculateProductSum(products); 25 | 26 | Currency firstProductCurrency = products.get(0).getAmount() 27 | .getCurrency(); 28 | 29 | return new AmountImpl(productSum, firstProductCurrency); 30 | } 31 | 32 | private BigDecimal calculateProductSum(List products) { 33 | BigDecimal sum = BigDecimal.ZERO; 34 | // Calculate Sum of Products 35 | for (Product product : products) { 36 | sum = sum.add(product.getAmount().getValue()); 37 | } 38 | return sum; 39 | } 40 | 41 | private boolean isCurrencySameForAllProducts(List products) 42 | throws DifferentCurrenciesException { 43 | 44 | Currency firstProductCurrency = products.get(0).getAmount() 45 | .getCurrency(); 46 | 47 | for (Product product : products) { 48 | boolean currencySameAsFirstProduct = product.getAmount() 49 | .getCurrency().equals(firstProductCurrency); 50 | if (!currencySameAsFirstProduct) { 51 | return false; 52 | } 53 | } 54 | 55 | return true; 56 | } 57 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/business/exception/DifferentCurrenciesException.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.business.exception; 2 | 3 | public class DifferentCurrenciesException extends Exception { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = 1L; 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/helper/StringHelper.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.helper; 2 | 3 | public class StringHelper { 4 | 5 | public String truncateAInFirst2Positions(String str) { 6 | if (str.length() <= 2) 7 | return str.replaceAll("A", ""); 8 | 9 | String first2Chars = str.substring(0, 2); 10 | String stringMinusFirst2Chars = str.substring(2); 11 | 12 | return first2Chars.replaceAll("A", "") + stringMinusFirst2Chars; 13 | } 14 | 15 | public boolean areFirstAndLastTwoCharactersTheSame(String str) { 16 | 17 | if (str.length() <= 1) 18 | return false; 19 | if (str.length() == 2) 20 | return true; 21 | 22 | String first2Chars = str.substring(0, 2); 23 | 24 | String last2Chars = str.substring(str.length() - 2); 25 | 26 | return first2Chars.equals(last2Chars); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/Amount.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public interface Amount { 6 | BigDecimal getValue(); 7 | 8 | Currency getCurrency(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/AmountImpl.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public class AmountImpl implements Amount { 6 | 7 | BigDecimal value; 8 | Currency currency; 9 | 10 | public AmountImpl(BigDecimal value, Currency currency) { 11 | super(); 12 | this.value = value; 13 | this.currency = currency; 14 | } 15 | 16 | public void setValue(BigDecimal value) { 17 | this.value = value; 18 | } 19 | 20 | @Override 21 | public BigDecimal getValue() { 22 | return value; 23 | } 24 | 25 | public void setCurrency(Currency currency) { 26 | this.currency = currency; 27 | } 28 | 29 | @Override 30 | public Currency getCurrency() { 31 | return currency; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/Client.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.List; 5 | 6 | /** 7 | * Client Model API. 8 | */ 9 | public interface Client { 10 | 11 | long getId(); 12 | 13 | String getName(); 14 | 15 | Enum getType(); 16 | 17 | List getCollaterals(); 18 | 19 | List getProducts(); 20 | 21 | void setProductAmount(BigDecimal productAmount); 22 | 23 | BigDecimal getProductAmount(); 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/ClientImpl.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.List; 5 | 6 | /** 7 | * Client Model API. 8 | */ 9 | public class ClientImpl implements Client { 10 | 11 | private long id; 12 | 13 | private String name; 14 | 15 | private ClientType type; 16 | 17 | private List collaterals; 18 | 19 | private List products; 20 | 21 | private BigDecimal productAmount; 22 | 23 | public ClientImpl(long id, String name, ClientType type, 24 | List collaterals, List products) { 25 | super(); 26 | this.id = id; 27 | this.name = name; 28 | this.type = type; 29 | this.collaterals = collaterals; 30 | this.products = products; 31 | } 32 | 33 | public long getId() { 34 | return id; 35 | } 36 | 37 | public void setId(long id) { 38 | this.id = id; 39 | } 40 | 41 | @Override 42 | public String getName() { 43 | return name; 44 | } 45 | 46 | public void setName(String name) { 47 | this.name = name; 48 | } 49 | 50 | @Override 51 | public ClientType getType() { 52 | return type; 53 | } 54 | 55 | public void setType(ClientType type) { 56 | this.type = type; 57 | } 58 | 59 | @Override 60 | public List getCollaterals() { 61 | return collaterals; 62 | } 63 | 64 | public void setCollaterals(List collaterals) { 65 | this.collaterals = collaterals; 66 | } 67 | 68 | @Override 69 | public List getProducts() { 70 | return products; 71 | } 72 | 73 | public void setProducts(List products) { 74 | this.products = products; 75 | } 76 | 77 | @Override 78 | public BigDecimal getProductAmount() { 79 | return productAmount; 80 | } 81 | 82 | @Override 83 | public void setProductAmount(BigDecimal productAmount) { 84 | this.productAmount = productAmount; 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/ClientType.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * Available types of customers 8 | */ 9 | public enum ClientType { 10 | /** 11 | * 12 | */ 13 | PRIVATE("P"), 14 | /** 15 | * 16 | */ 17 | BUSINESS("Z"); 18 | 19 | private final String textValue; 20 | 21 | /** 22 | * List of natural person types. 23 | */ 24 | public static final List NATURAL_PERSON_TYPES = Arrays 25 | .asList(ClientType.PRIVATE.toString()); 26 | 27 | /** 28 | * List of corporate types. 29 | */ 30 | public static final List CORPORATE_TYPES = Arrays 31 | .asList(ClientType.BUSINESS.toString()); 32 | 33 | ClientType(final String textValue) { 34 | this.textValue = textValue; 35 | } 36 | 37 | @Override 38 | public String toString() { 39 | return textValue; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/Collateral.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | /** 4 | * Collateral Model API. 5 | */ 6 | public interface Collateral { 7 | 8 | long getId(); 9 | 10 | String getName(); 11 | 12 | CollateralType getType(); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/CollateralImpl.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | /** 4 | * Collateral Model Object. 5 | */ 6 | public class CollateralImpl implements Collateral { 7 | 8 | private long id; 9 | 10 | private String name; 11 | 12 | private CollateralType type; 13 | 14 | public CollateralImpl(long id, String name, CollateralType type) { 15 | super(); 16 | this.id = id; 17 | this.name = name; 18 | this.type = type; 19 | } 20 | 21 | public long getId() { 22 | return id; 23 | } 24 | 25 | public void setId(long id) { 26 | this.id = id; 27 | } 28 | 29 | @Override 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | @Override 39 | public CollateralType getType() { 40 | return type; 41 | } 42 | 43 | public void setType(CollateralType type) { 44 | this.type = type; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/CollateralType.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | /** 7 | * Available types of customers 8 | */ 9 | public enum CollateralType { 10 | REAL_ESTATE("REA"), BONDS("BND"), MUTUAL_FUNDS("MFD"), STOCKS("STK"); 11 | 12 | private final String textValue; 13 | 14 | /** 15 | * All collateral types classified as securities. 16 | */ 17 | public static final List SECURITIES = Arrays.asList(BONDS, 18 | MUTUAL_FUNDS, STOCKS); 19 | 20 | CollateralType(final String textValue) { 21 | this.textValue = textValue; 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | return textValue; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/Currency.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | public enum Currency { 4 | 5 | EURO("EUR"), UNITED_STATES_DOLLAR("USD"), INDIAN_RUPEE("INR"); 6 | 7 | private final String textValue; 8 | 9 | Currency(final String textValue) { 10 | this.textValue = textValue; 11 | } 12 | 13 | @Override 14 | public String toString() { 15 | return textValue; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/Product.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | /** 4 | * Product Model API. 5 | */ 6 | public interface Product { 7 | 8 | long getId(); 9 | 10 | String getName(); 11 | 12 | ProductType getType(); 13 | 14 | Amount getAmount(); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/ProductImpl.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | /** 4 | * Collateral Model Object. 5 | */ 6 | public class ProductImpl implements Product { 7 | 8 | private long id; 9 | 10 | private String name; 11 | 12 | private ProductType type; 13 | 14 | private Amount amount; 15 | 16 | public ProductImpl(long id, String name, ProductType type, Amount amount) { 17 | super(); 18 | this.id = id; 19 | this.name = name; 20 | this.type = type; 21 | this.amount = amount; 22 | } 23 | 24 | @Override 25 | public long getId() { 26 | return id; 27 | } 28 | 29 | public void setId(long id) { 30 | this.id = id; 31 | } 32 | 33 | @Override 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | @Override 43 | public ProductType getType() { 44 | return type; 45 | } 46 | 47 | public void setType(ProductType type) { 48 | this.type = type; 49 | } 50 | 51 | @Override 52 | public Amount getAmount() { 53 | return amount; 54 | } 55 | 56 | public void setAmount(Amount amount) { 57 | this.amount = amount; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/junit/model/ProductType.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.model; 2 | 3 | /** 4 | * Available types of customers 5 | */ 6 | public enum ProductType { 7 | LOAN("LN"), KREDIT("KRD"), BANK_GUARANTEE("BG"); 8 | 9 | private final String textValue; 10 | 11 | ProductType(final String textValue) { 12 | this.textValue = textValue; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return textValue; 18 | } 19 | } -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/powermock/SystemUnderTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.powermock; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | interface Dependency { 7 | List retrieveAllStats(); 8 | } 9 | 10 | public class SystemUnderTest { 11 | private Dependency dependency; 12 | 13 | public int methodUsingAnArrayListConstructor() { 14 | ArrayList list = new ArrayList(); 15 | return list.size(); 16 | } 17 | 18 | public int methodCallingAStaticMethod() { 19 | //privateMethodUnderTest calls static method SomeClass.staticMethod 20 | List stats = dependency.retrieveAllStats(); 21 | long sum = 0; 22 | for (int stat : stats) 23 | sum += stat; 24 | return UtilityClass.staticMethod(sum); 25 | } 26 | 27 | private long privateMethodUnderTest() { 28 | List stats = dependency.retrieveAllStats(); 29 | long sum = 0; 30 | for (int stat : stats) 31 | sum += stat; 32 | return sum; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/in28minutes/powermock/UtilityClass.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.powermock; 2 | 3 | public class UtilityClass { 4 | static int staticMethod(long value) { 5 | // Some complex logic is done here... 6 | throw new RuntimeException( 7 | "I dont want to be executed. I will anyway be mocked out."); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/test/java/com/clarity/business/ClientBOTest.java: -------------------------------------------------------------------------------- 1 | package com.clarity.business; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.junit.Assert.fail; 5 | 6 | import java.math.BigDecimal; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | import org.junit.Test; 11 | 12 | import com.in28minutes.junit.business.ClientBO; 13 | import com.in28minutes.junit.business.ClientBOImpl; 14 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 15 | import com.in28minutes.junit.model.Amount; 16 | import com.in28minutes.junit.model.AmountImpl; 17 | import com.in28minutes.junit.model.Currency; 18 | import com.in28minutes.junit.model.Product; 19 | import com.in28minutes.junit.model.ProductImpl; 20 | import com.in28minutes.junit.model.ProductType; 21 | 22 | public class ClientBOTest { 23 | 24 | private ClientBO clientBO = new ClientBOImpl(); 25 | 26 | @Test 27 | public void testClientProductSum() throws DifferentCurrenciesException { 28 | 29 | List products = new ArrayList(); 30 | 31 | products.add(new ProductImpl(100, "Product 15", 32 | ProductType.BANK_GUARANTEE, new AmountImpl( 33 | new BigDecimal("5.0"), Currency.EURO))); 34 | 35 | products.add(new ProductImpl(120, "Product 20", 36 | ProductType.BANK_GUARANTEE, new AmountImpl( 37 | new BigDecimal("6.0"), Currency.EURO))); 38 | 39 | Amount temp = clientBO.getClientProductsSum(products); 40 | 41 | assertEquals(Currency.EURO, temp.getCurrency()); 42 | assertEquals(new BigDecimal("11.0"), temp.getValue()); 43 | } 44 | 45 | @Test(expected = DifferentCurrenciesException.class) 46 | public void testClientProductSum1() throws DifferentCurrenciesException { 47 | 48 | List products = new ArrayList(); 49 | 50 | products.add(new ProductImpl(100, "Product 15", 51 | ProductType.BANK_GUARANTEE, new AmountImpl( 52 | new BigDecimal("5.0"), Currency.INDIAN_RUPEE))); 53 | 54 | products.add(new ProductImpl(120, "Product 20", 55 | ProductType.BANK_GUARANTEE, new AmountImpl( 56 | new BigDecimal("6.0"), Currency.EURO))); 57 | 58 | @SuppressWarnings("unused") 59 | Amount temp = null; 60 | 61 | temp = clientBO.getClientProductsSum(products); 62 | } 63 | 64 | @Test 65 | public void testClientProductSum2() { 66 | 67 | List products = new ArrayList(); 68 | 69 | Amount temp = null; 70 | 71 | try { 72 | temp = clientBO.getClientProductsSum(products); 73 | } catch (DifferentCurrenciesException e) { 74 | } 75 | assertEquals(Currency.EURO, temp.getCurrency()); 76 | assertEquals(BigDecimal.ZERO, temp.getValue()); 77 | } 78 | 79 | } -------------------------------------------------------------------------------- /src/test/java/com/clarity/business/ClientBOTestRefactored.java: -------------------------------------------------------------------------------- 1 | package com.clarity.business; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import java.math.BigDecimal; 6 | import java.util.ArrayList; 7 | import java.util.List; 8 | 9 | import org.junit.Test; 10 | 11 | import com.in28minutes.junit.business.ClientBO; 12 | import com.in28minutes.junit.business.ClientBOImpl; 13 | import com.in28minutes.junit.business.exception.DifferentCurrenciesException; 14 | import com.in28minutes.junit.model.Amount; 15 | import com.in28minutes.junit.model.AmountImpl; 16 | import com.in28minutes.junit.model.Currency; 17 | import com.in28minutes.junit.model.Product; 18 | import com.in28minutes.junit.model.ProductImpl; 19 | import com.in28minutes.junit.model.ProductType; 20 | 21 | public class ClientBOTestRefactored { 22 | 23 | private ClientBO clientBO = new ClientBOImpl(); 24 | 25 | @Test 26 | public void testClientProductSum_AllProductsSameCurrency() 27 | throws DifferentCurrenciesException { 28 | 29 | Amount[] amounts = { 30 | new AmountImpl(new BigDecimal("5.0"), Currency.EURO), 31 | new AmountImpl(new BigDecimal("6.0"), Currency.EURO) }; 32 | 33 | Amount expected = new AmountImpl(new BigDecimal("11.0"), Currency.EURO); 34 | 35 | List products = createProductListWithAmounts(amounts); 36 | 37 | Amount actual = clientBO.getClientProductsSum(products); 38 | 39 | assertAmount(actual, expected); 40 | } 41 | 42 | @Test(expected = DifferentCurrenciesException.class) 43 | public void testClientProductSum_DifferentCurrencies_ThrowsException() 44 | throws DifferentCurrenciesException { 45 | 46 | Amount[] amounts = { 47 | new AmountImpl(new BigDecimal("5.0"), Currency.EURO), 48 | new AmountImpl(new BigDecimal("6.0"), Currency.INDIAN_RUPEE) }; 49 | 50 | List products = createProductListWithAmounts(amounts); 51 | 52 | @SuppressWarnings("unused") 53 | Amount actual = clientBO.getClientProductsSum(products); 54 | 55 | } 56 | 57 | @Test 58 | public void testClientProductSum_NoProducts() 59 | throws DifferentCurrenciesException { 60 | 61 | Amount[] amounts = {}; 62 | Amount expected = new AmountImpl(BigDecimal.ZERO, Currency.EURO); 63 | 64 | List products = createProductListWithAmounts(amounts); 65 | 66 | Amount actual = clientBO.getClientProductsSum(products); 67 | 68 | 69 | assertAmount(actual, expected); 70 | } 71 | 72 | private void assertAmount(Amount actual, Amount expected) { 73 | assertEquals(expected.getCurrency(), actual.getCurrency()); 74 | assertEquals(expected.getValue(), actual.getValue()); 75 | } 76 | 77 | private List createProductListWithAmounts(Amount[] amounts) { 78 | List products = new ArrayList(); 79 | for (Amount amount : amounts) { 80 | products.add(new ProductImpl(100, "Product 15", 81 | ProductType.BANK_GUARANTEE, amount)); 82 | } 83 | return products; 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoInjectMocksTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.business; 2 | 3 | import static org.hamcrest.CoreMatchers.is; 4 | import static org.junit.Assert.assertEquals; 5 | import static org.junit.Assert.assertThat; 6 | import static org.mockito.BDDMockito.given; 7 | import static org.mockito.Mockito.verify; 8 | import static org.mockito.Mockito.when; 9 | 10 | import java.util.Arrays; 11 | import java.util.List; 12 | 13 | import org.junit.Test; 14 | import org.junit.runner.RunWith; 15 | import org.mockito.ArgumentCaptor; 16 | import org.mockito.Captor; 17 | import org.mockito.InjectMocks; 18 | import org.mockito.Mock; 19 | import org.mockito.Mockito; 20 | import org.mockito.runners.MockitoJUnitRunner; 21 | 22 | import com.in28minutes.data.api.TodoService; 23 | 24 | @RunWith(MockitoJUnitRunner.class) 25 | public class TodoBusinessImplMockitoInjectMocksTest { 26 | @Mock 27 | TodoService todoService; 28 | 29 | @InjectMocks 30 | TodoBusinessImpl todoBusinessImpl; 31 | 32 | @Captor 33 | ArgumentCaptor stringArgumentCaptor; 34 | 35 | @Test 36 | public void usingMockito() { 37 | List allTodos = Arrays.asList("Learn Spring MVC", 38 | "Learn Spring", "Learn to Dance"); 39 | 40 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 41 | 42 | List todos = todoBusinessImpl 43 | .retrieveTodosRelatedToSpring("Ranga"); 44 | assertEquals(2, todos.size()); 45 | } 46 | 47 | @Test 48 | public void usingMockito_UsingBDD() { 49 | List allTodos = Arrays.asList("Learn Spring MVC", 50 | "Learn Spring", "Learn to Dance"); 51 | 52 | //given 53 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 54 | 55 | //when 56 | List todos = todoBusinessImpl 57 | .retrieveTodosRelatedToSpring("Ranga"); 58 | 59 | //then 60 | assertThat(todos.size(), is(2)); 61 | } 62 | 63 | @Test 64 | public void letsTestDeleteNow() { 65 | 66 | List allTodos = Arrays.asList("Learn Spring MVC", 67 | "Learn Spring", "Learn to Dance"); 68 | 69 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 70 | 71 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 72 | 73 | verify(todoService).deleteTodo("Learn to Dance"); 74 | 75 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 76 | 77 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 78 | 79 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 80 | // atLeastOnce, atLeast 81 | 82 | } 83 | 84 | @Test 85 | public void captureArgument() { 86 | List allTodos = Arrays.asList("Learn Spring MVC", 87 | "Learn Spring", "Learn to Dance"); 88 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 89 | 90 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 91 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 92 | 93 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoRulesTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.business; 2 | 3 | import static org.hamcrest.CoreMatchers.is; 4 | import static org.junit.Assert.assertEquals; 5 | import static org.junit.Assert.assertThat; 6 | import static org.mockito.BDDMockito.given; 7 | import static org.mockito.Mockito.verify; 8 | import static org.mockito.Mockito.when; 9 | 10 | import java.util.Arrays; 11 | import java.util.List; 12 | 13 | import org.junit.Rule; 14 | import org.junit.Test; 15 | import org.mockito.ArgumentCaptor; 16 | import org.mockito.Captor; 17 | import org.mockito.InjectMocks; 18 | import org.mockito.Mock; 19 | import org.mockito.Mockito; 20 | import org.mockito.junit.MockitoJUnit; 21 | import org.mockito.junit.MockitoRule; 22 | 23 | import com.in28minutes.data.api.TodoService; 24 | 25 | public class TodoBusinessImplMockitoRulesTest { 26 | 27 | @Rule 28 | public MockitoRule mockitoRule = MockitoJUnit.rule(); 29 | 30 | @Mock 31 | TodoService todoService; 32 | 33 | @InjectMocks 34 | TodoBusinessImpl todoBusinessImpl; 35 | 36 | @Captor 37 | ArgumentCaptor stringArgumentCaptor; 38 | 39 | @Test 40 | public void usingMockito() { 41 | List allTodos = Arrays.asList("Learn Spring MVC", 42 | "Learn Spring", "Learn to Dance"); 43 | 44 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 45 | 46 | List todos = todoBusinessImpl 47 | .retrieveTodosRelatedToSpring("Ranga"); 48 | assertEquals(2, todos.size()); 49 | } 50 | 51 | @Test 52 | public void usingMockito_UsingBDD() { 53 | List allTodos = Arrays.asList("Learn Spring MVC", 54 | "Learn Spring", "Learn to Dance"); 55 | 56 | //given 57 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 58 | 59 | //when 60 | List todos = todoBusinessImpl 61 | .retrieveTodosRelatedToSpring("Ranga"); 62 | 63 | //then 64 | assertThat(todos.size(), is(2)); 65 | } 66 | 67 | @Test 68 | public void letsTestDeleteNow() { 69 | 70 | List allTodos = Arrays.asList("Learn Spring MVC", 71 | "Learn Spring", "Learn to Dance"); 72 | 73 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 74 | 75 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 76 | 77 | verify(todoService).deleteTodo("Learn to Dance"); 78 | 79 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 80 | 81 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 82 | 83 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 84 | // atLeastOnce, atLeast 85 | 86 | } 87 | 88 | @Test 89 | public void captureArgument() { 90 | List allTodos = Arrays.asList("Learn Spring MVC", 91 | "Learn Spring", "Learn to Dance"); 92 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 93 | 94 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 95 | Mockito.verify(todoService).deleteTodo(stringArgumentCaptor.capture()); 96 | 97 | assertEquals("Learn to Dance", stringArgumentCaptor.getValue()); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/business/TodoBusinessImplMockitoTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.business; 2 | 3 | import static org.hamcrest.CoreMatchers.is; 4 | import static org.junit.Assert.assertEquals; 5 | import static org.junit.Assert.assertThat; 6 | import static org.mockito.BDDMockito.given; 7 | import static org.mockito.Mockito.mock; 8 | import static org.mockito.Mockito.verify; 9 | import static org.mockito.Mockito.when; 10 | 11 | import java.util.Arrays; 12 | import java.util.List; 13 | 14 | import org.junit.Test; 15 | import org.mockito.ArgumentCaptor; 16 | import org.mockito.Mockito; 17 | 18 | import com.in28minutes.data.api.TodoService; 19 | 20 | public class TodoBusinessImplMockitoTest { 21 | 22 | @Test 23 | public void usingMockito() { 24 | TodoService todoService = mock(TodoService.class); 25 | List allTodos = Arrays.asList("Learn Spring MVC", 26 | "Learn Spring", "Learn to Dance"); 27 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 28 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 29 | List todos = todoBusinessImpl 30 | .retrieveTodosRelatedToSpring("Ranga"); 31 | assertEquals(2, todos.size()); 32 | } 33 | 34 | @Test 35 | public void usingMockito_UsingBDD() { 36 | TodoService todoService = mock(TodoService.class); 37 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 38 | List allTodos = Arrays.asList("Learn Spring MVC", 39 | "Learn Spring", "Learn to Dance"); 40 | 41 | //given 42 | given(todoService.retrieveTodos("Ranga")).willReturn(allTodos); 43 | 44 | //when 45 | List todos = todoBusinessImpl 46 | .retrieveTodosRelatedToSpring("Ranga"); 47 | 48 | //then 49 | assertThat(todos.size(), is(2)); 50 | } 51 | 52 | @Test 53 | public void letsTestDeleteNow() { 54 | 55 | TodoService todoService = mock(TodoService.class); 56 | 57 | List allTodos = Arrays.asList("Learn Spring MVC", 58 | "Learn Spring", "Learn to Dance"); 59 | 60 | when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 61 | 62 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 63 | 64 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 65 | 66 | verify(todoService).deleteTodo("Learn to Dance"); 67 | 68 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring MVC"); 69 | 70 | verify(todoService, Mockito.never()).deleteTodo("Learn Spring"); 71 | 72 | verify(todoService, Mockito.times(1)).deleteTodo("Learn to Dance"); 73 | // atLeastOnce, atLeast 74 | 75 | } 76 | 77 | @Test 78 | public void captureArgument() { 79 | ArgumentCaptor argumentCaptor = ArgumentCaptor 80 | .forClass(String.class); 81 | 82 | TodoService todoService = mock(TodoService.class); 83 | 84 | List allTodos = Arrays.asList("Learn Spring MVC", 85 | "Learn Spring", "Learn to Dance"); 86 | Mockito.when(todoService.retrieveTodos("Ranga")).thenReturn(allTodos); 87 | 88 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 89 | todoBusinessImpl.deleteTodosNotRelatedToSpring("Ranga"); 90 | Mockito.verify(todoService).deleteTodo(argumentCaptor.capture()); 91 | 92 | assertEquals("Learn to Dance", argumentCaptor.getValue()); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/business/TodoBusinessImplStubTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.business; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import java.util.List; 6 | 7 | import org.junit.Test; 8 | 9 | import com.in28minutes.data.api.TodoService; 10 | import com.in28minutes.data.stub.TodoServiceStub; 11 | 12 | public class TodoBusinessImplStubTest { 13 | 14 | @Test 15 | public void usingAStub() { 16 | TodoService todoService = new TodoServiceStub(); 17 | TodoBusinessImpl todoBusinessImpl = new TodoBusinessImpl(todoService); 18 | List todos = todoBusinessImpl 19 | .retrieveTodosRelatedToSpring("Ranga"); 20 | assertEquals(2, todos.size()); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/data/stub/TodoServiceStub.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.data.stub; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import com.in28minutes.data.api.TodoService; 7 | 8 | public class TodoServiceStub implements TodoService { 9 | public List retrieveTodos(String user) { 10 | return Arrays.asList("Learn Spring MVC", "Learn Spring", 11 | "Learn to Dance"); 12 | } 13 | 14 | public void deleteTodo(String todo) { 15 | 16 | } 17 | } -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/junit/helper/ArraysCompareTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.helper; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.Arrays; 6 | 7 | import org.junit.Test; 8 | 9 | public class ArraysCompareTest { 10 | 11 | @Test 12 | public void testArraySort_RandomArray() { 13 | int[] numbers = { 12, 3, 4, 1 }; 14 | int[] expected = { 1, 3, 4, 12 }; 15 | Arrays.sort(numbers); 16 | assertArrayEquals(expected, numbers); 17 | } 18 | 19 | @Test(expected=NullPointerException.class) 20 | public void testArraySort_NullArray() { 21 | int[] numbers = null; 22 | Arrays.sort(numbers); 23 | } 24 | 25 | @Test(timeout=100) 26 | public void testSort_Performance(){ 27 | int array[] = {12,23,4}; 28 | for(int i=1;i<=1000000;i++) 29 | { 30 | array[0] = i; 31 | Arrays.sort(array); 32 | } 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/junit/helper/ArraysTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.helper; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | 6 | import java.util.Arrays; 7 | 8 | import org.junit.Test; 9 | 10 | public class ArraysTest { 11 | @Test(timeout=100) 12 | public void testPerformance() { 13 | for(int i=0;i<1000000;i++){ 14 | Arrays.sort(new int[]{i,i-1,i+1}); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/junit/helper/QuickBeforeAfterTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.helper; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.After; 6 | import org.junit.AfterClass; 7 | import org.junit.Before; 8 | import org.junit.BeforeClass; 9 | import org.junit.Test; 10 | 11 | public class QuickBeforeAfterTest { 12 | 13 | @BeforeClass 14 | public static void beforeClass(){ 15 | System.out.println("Before Class"); 16 | } 17 | 18 | @Before 19 | public void setup(){ 20 | System.out.println("Before Test"); 21 | } 22 | 23 | @Test 24 | public void test1() { 25 | System.out.println("test1 executed"); 26 | } 27 | 28 | @Test 29 | public void test2() { 30 | System.out.println("test2 executed"); 31 | } 32 | 33 | @After 34 | public void teardown() { 35 | System.out.println("After test"); 36 | } 37 | 38 | @AfterClass 39 | public static void afterClass(){ 40 | System.out.println("After Class"); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/junit/helper/StringHelperParameterizedTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.helper; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import java.util.Arrays; 6 | import java.util.Collection; 7 | 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.junit.runners.Parameterized; 12 | import org.junit.runners.Parameterized.Parameters; 13 | 14 | @RunWith(Parameterized.class) 15 | public class StringHelperParameterizedTest { 16 | 17 | // AACD => CD ACD => CD CDEF=>CDEF CDAA => CDAA 18 | 19 | StringHelper helper = new StringHelper(); 20 | 21 | private String input; 22 | private String expectedOutput; 23 | 24 | public StringHelperParameterizedTest(String input, String expectedOutput) { 25 | this.input = input; 26 | this.expectedOutput = expectedOutput; 27 | } 28 | 29 | @Parameters 30 | public static Collection testConditions() { 31 | String expectedOutputs[][] = { 32 | { "AACD", "CD" }, 33 | { "ACD", "CD" } }; 34 | return Arrays.asList(expectedOutputs); 35 | } 36 | 37 | @Test 38 | public void testTruncateAInFirst2Positions() { 39 | assertEquals(expectedOutput, 40 | helper.truncateAInFirst2Positions(input)); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/junit/helper/StringHelperTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.helper; 2 | 3 | import static org.junit.Assert.*; 4 | 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | 8 | public class StringHelperTest { 9 | 10 | // AACD => CD ACD => CD CDEF=>CDEF CDAA => CDAA 11 | 12 | StringHelper helper; 13 | 14 | @Before 15 | public void before(){ 16 | helper = new StringHelper(); 17 | } 18 | 19 | 20 | @Test 21 | public void testTruncateAInFirst2Positions_AinFirst2Positions() { 22 | assertEquals("CD", helper.truncateAInFirst2Positions("AACD")); 23 | } 24 | 25 | @Test 26 | public void testTruncateAInFirst2Positions_AinFirstPosition() { 27 | assertEquals("CD", helper.truncateAInFirst2Positions("ACD")); 28 | } 29 | 30 | // ABCD => false, ABAB => true, AB => true, A => false 31 | @Test 32 | public void testAreFirstAndLastTwoCharactersTheSame_BasicNegativeScenario() { 33 | assertFalse( 34 | helper.areFirstAndLastTwoCharactersTheSame("ABCD")); 35 | } 36 | 37 | @Test 38 | public void testAreFirstAndLastTwoCharactersTheSame_BasicPositiveScenario() { 39 | assertTrue( 40 | helper.areFirstAndLastTwoCharactersTheSame("ABAB")); 41 | } 42 | 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/junit/suite/DummyTestSuite.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.junit.suite; 2 | 3 | import org.junit.runner.RunWith; 4 | import org.junit.runners.Suite; 5 | import org.junit.runners.Suite.SuiteClasses; 6 | 7 | import com.in28minutes.junit.helper.ArraysTest; 8 | import com.in28minutes.junit.helper.StringHelperTest; 9 | 10 | @RunWith(Suite.class) 11 | @SuiteClasses({ArraysTest.class,StringHelperTest.class}) 12 | public class DummyTestSuite { 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/mockito/FirstMockitoTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.mockito; 2 | 3 | import static org.junit.Assert.assertTrue; 4 | 5 | import org.junit.Test; 6 | 7 | public class FirstMockitoTest { 8 | 9 | @Test 10 | public void test() { 11 | assertTrue(true); 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/mockito/HamcrestMatcherTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.mockito; 2 | 3 | import static org.hamcrest.CoreMatchers.hasItems; 4 | import static org.hamcrest.MatcherAssert.assertThat; 5 | import static org.hamcrest.Matchers.arrayContainingInAnyOrder; 6 | import static org.hamcrest.Matchers.arrayWithSize; 7 | import static org.hamcrest.Matchers.greaterThan; 8 | import static org.hamcrest.Matchers.hasSize; 9 | import static org.hamcrest.Matchers.isEmptyOrNullString; 10 | import static org.hamcrest.Matchers.isEmptyString; 11 | import static org.hamcrest.Matchers.lessThan; 12 | import static org.hamcrest.core.Every.everyItem; 13 | 14 | import java.util.Arrays; 15 | import java.util.List; 16 | 17 | import org.junit.Test; 18 | 19 | public class HamcrestMatcherTest { 20 | 21 | @Test 22 | public void basicHamcrestMatchers() { 23 | List scores = Arrays.asList(99, 100, 101, 105); 24 | assertThat(scores, hasSize(4)); 25 | assertThat(scores, hasItems(100, 101)); 26 | assertThat(scores, everyItem(greaterThan(90))); 27 | assertThat(scores, everyItem(lessThan(200))); 28 | 29 | // String 30 | assertThat("", isEmptyString()); 31 | assertThat(null, isEmptyOrNullString()); 32 | 33 | // Array 34 | Integer[] marks = { 1, 2, 3 }; 35 | 36 | assertThat(marks, arrayWithSize(3)); 37 | assertThat(marks, arrayContainingInAnyOrder(2, 3, 1)); 38 | 39 | } 40 | } -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/mockito/ListTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.mockito; 2 | 3 | import static org.hamcrest.CoreMatchers.is; 4 | import static org.junit.Assert.assertEquals; 5 | import static org.junit.Assert.assertNull; 6 | import static org.junit.Assert.assertThat; 7 | import static org.mockito.BDDMockito.given; 8 | import static org.mockito.Mockito.mock; 9 | import static org.mockito.Mockito.when; 10 | 11 | import java.util.List; 12 | 13 | import org.junit.Test; 14 | import org.mockito.Mockito; 15 | 16 | public class ListTest { 17 | 18 | @Test 19 | public void letsMockListSize() { 20 | List list = mock(List.class); 21 | when(list.size()).thenReturn(10); 22 | assertEquals(10, list.size()); 23 | } 24 | 25 | @Test 26 | public void letsMockListSizeWithMultipleReturnValues() { 27 | List list = mock(List.class); 28 | when(list.size()).thenReturn(10).thenReturn(20); 29 | assertEquals(10, list.size()); // First Call 30 | assertEquals(20, list.size()); // Second Call 31 | } 32 | 33 | @Test 34 | public void letsMockListGet() { 35 | List list = mock(List.class); 36 | when(list.get(0)).thenReturn("in28Minutes"); 37 | assertEquals("in28Minutes", list.get(0)); 38 | assertNull(list.get(1)); 39 | } 40 | 41 | @Test(expected = RuntimeException.class) 42 | public void letsMockListGetToThrowException() { 43 | List list = mock(List.class); 44 | when(list.get(Mockito.anyInt())).thenThrow( 45 | new RuntimeException("Something went wrong")); 46 | list.get(0); 47 | } 48 | 49 | @Test 50 | public void letsMockListGetWithAny() { 51 | List list = mock(List.class); 52 | Mockito.when(list.get(Mockito.anyInt())).thenReturn("in28Minutes"); 53 | // If you are using argument matchers, all arguments 54 | // have to be provided by matchers. 55 | assertEquals("in28Minutes", list.get(0)); 56 | assertEquals("in28Minutes", list.get(1)); 57 | } 58 | 59 | @Test 60 | public void bddAliases_UsingGivenWillReturn() { 61 | List list = mock(List.class); 62 | 63 | //given 64 | given(list.get(Mockito.anyInt())).willReturn("in28Minutes"); 65 | 66 | //then 67 | assertThat("in28Minutes", is(list.get(0))); 68 | assertThat("in28Minutes", is(list.get(0))); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/mockito/SpyTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.mockito; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.mockito.Mockito.spy; 5 | import static org.mockito.Mockito.stub; 6 | import static org.mockito.Mockito.verify; 7 | 8 | import java.util.ArrayList; 9 | import java.util.List; 10 | 11 | import org.junit.Test; 12 | 13 | public class SpyTest { 14 | 15 | @Test 16 | public void creatingASpyOnArrayList() { 17 | List listSpy = spy(ArrayList.class); 18 | listSpy.add("Ranga"); 19 | listSpy.add("in28Minutes"); 20 | 21 | verify(listSpy).add("Ranga"); 22 | verify(listSpy).add("in28Minutes"); 23 | 24 | assertEquals(2, listSpy.size()); 25 | assertEquals("Ranga", listSpy.get(0)); 26 | } 27 | 28 | @Test 29 | public void creatingASpyOnArrayList_overridingSpecificMethods() { 30 | List listSpy = spy(ArrayList.class); 31 | listSpy.add("Ranga"); 32 | listSpy.add("in28Minutes"); 33 | 34 | stub(listSpy.size()).toReturn(-1); 35 | 36 | assertEquals(-1, listSpy.size()); 37 | assertEquals("Ranga", listSpy.get(0)); 38 | 39 | // @Spy Annotation 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/powermock/PowerMockitoMockingConstructorTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.powermock; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.mockito.Mockito.mock; 5 | import static org.mockito.Mockito.stub; 6 | 7 | import java.util.ArrayList; 8 | 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.mockito.InjectMocks; 12 | import org.mockito.Mock; 13 | import org.powermock.api.mockito.PowerMockito; 14 | import org.powermock.core.classloader.annotations.PrepareForTest; 15 | import org.powermock.modules.junit4.PowerMockRunner; 16 | 17 | @RunWith(PowerMockRunner.class) 18 | @PrepareForTest({ SystemUnderTest.class /*To be able to mock the Constructor, we need to add in the Class that creates the new object*/}) 19 | public class PowerMockitoMockingConstructorTest { 20 | 21 | private static final int SOME_DUMMY_SIZE = 100; 22 | 23 | @Mock 24 | Dependency dependencyMock; 25 | 26 | @InjectMocks 27 | SystemUnderTest systemUnderTest; 28 | 29 | @Test 30 | public void powerMockito_MockingAConstructor() throws Exception { 31 | 32 | ArrayList mockList = mock(ArrayList.class); 33 | 34 | stub(mockList.size()).toReturn(SOME_DUMMY_SIZE); 35 | 36 | PowerMockito.whenNew(ArrayList.class).withAnyArguments().thenReturn( 37 | mockList); 38 | 39 | int size = systemUnderTest.methodUsingAnArrayListConstructor(); 40 | 41 | assertEquals(SOME_DUMMY_SIZE, size); 42 | } 43 | } -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/powermock/PowerMockitoMockingStaticMethodTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.powermock; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.mockito.Matchers.anyLong; 5 | import static org.mockito.Mockito.when; 6 | 7 | import java.util.Arrays; 8 | 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.mockito.InjectMocks; 12 | import org.mockito.Mock; 13 | import org.powermock.api.mockito.PowerMockito; 14 | import org.powermock.core.classloader.annotations.PrepareForTest; 15 | import org.powermock.modules.junit4.PowerMockRunner; 16 | 17 | @RunWith(PowerMockRunner.class) 18 | @PrepareForTest({ UtilityClass.class /*The class with static method to be mocked*/}) 19 | public class PowerMockitoMockingStaticMethodTest { 20 | 21 | @Mock 22 | Dependency dependencyMock; 23 | 24 | @InjectMocks 25 | SystemUnderTest systemUnderTest; 26 | 27 | @Test 28 | public void powerMockito_MockingAStaticMethodCall() { 29 | 30 | when(dependencyMock.retrieveAllStats()).thenReturn( 31 | Arrays.asList(1, 2, 3)); 32 | 33 | PowerMockito.mockStatic(UtilityClass.class); 34 | 35 | when(UtilityClass.staticMethod(anyLong())).thenReturn(150); 36 | 37 | assertEquals(150, systemUnderTest.methodCallingAStaticMethod()); 38 | 39 | //To verify a specific method call 40 | //First : Call PowerMockito.verifyStatic() 41 | //Second : Call the method to be verified 42 | PowerMockito.verifyStatic(); 43 | UtilityClass.staticMethod(1 + 2 + 3); 44 | 45 | // verify exact number of calls 46 | //PowerMockito.verifyStatic(Mockito.times(1)); 47 | 48 | } 49 | } -------------------------------------------------------------------------------- /src/test/java/com/in28minutes/powermock/PowerMockitoTestingPrivateMethodTest.java: -------------------------------------------------------------------------------- 1 | package com.in28minutes.powermock; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | import static org.mockito.Mockito.when; 5 | 6 | import java.util.Arrays; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.mockito.InjectMocks; 11 | import org.mockito.Mock; 12 | import org.powermock.modules.junit4.PowerMockRunner; 13 | import org.powermock.reflect.Whitebox; 14 | 15 | @RunWith(PowerMockRunner.class) 16 | public class PowerMockitoTestingPrivateMethodTest { 17 | 18 | @Mock 19 | Dependency dependencyMock; 20 | 21 | @InjectMocks 22 | SystemUnderTest systemUnderTest; 23 | 24 | @Test 25 | public void powerMockito_CallingAPrivateMethod() throws Exception { 26 | when(dependencyMock.retrieveAllStats()).thenReturn( 27 | Arrays.asList(1, 2, 3)); 28 | long value = (Long) Whitebox.invokeMethod(systemUnderTest, 29 | "privateMethodUnderTest"); 30 | assertEquals(6, value); 31 | } 32 | } --------------------------------------------------------------------------------