├── .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 | [](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