Skip to content

Commit 1171d66

Browse files
authored
Merge pull request Vedenin#38 from HNKNTOC/master
Added example for Mockito.
2 parents b922340 + b85043c commit 1171d66

File tree

11 files changed

+390
-1
lines changed

11 files changed

+390
-1
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>4.1-testing</artifactId>
7+
<groupId>com.github.vedenin</groupId>
8+
<version>0.01</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>mockito</artifactId>
13+
14+
<description>This example to using Mockito for testing code.</description>
15+
16+
<properties>
17+
<java.version>1.7</java.version>
18+
<junit.version>4.12</junit.version>
19+
<maven.compiler.version>3.3</maven.compiler.version>
20+
<mockito.version>1.9.5</mockito.version>
21+
</properties>
22+
23+
<dependencies>
24+
<dependency>
25+
<groupId>junit</groupId>
26+
<artifactId>junit</artifactId>
27+
<version>${junit.version}</version>
28+
<scope>test</scope>
29+
</dependency>
30+
<dependency>
31+
<groupId>org.mockito</groupId>
32+
<artifactId>mockito-all</artifactId>
33+
<version>${mockito.version}</version>
34+
</dependency>
35+
</dependencies>
36+
37+
<build>
38+
<plugins>
39+
<plugin>
40+
<groupId>org.apache.maven.plugins</groupId>
41+
<artifactId>maven-compiler-plugin</artifactId>
42+
<version>${maven.compiler.version}</version>
43+
<configuration>
44+
<encoding>UTF-8</encoding>
45+
<source>${java.version}</source>
46+
<target>${java.version}</target>
47+
</configuration>
48+
</plugin>
49+
</plugins>
50+
</build>
51+
52+
</project>
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Calculate end cost on {@link Product}.
3+
* Performs operations with {@link Product} and {@link Client}.
4+
*/
5+
class Cashier {
6+
/**
7+
* Performs sale {@link Product}.
8+
* If {@link Client} cant buy {@link Product} report error in {@link Client}.
9+
*
10+
* @param client {@link Client} who want buy {@link Product}.
11+
* @param product {@link Product} which want buy {@link Client}.
12+
*/
13+
void toSell(Client client, Product product) {
14+
int cost = product.getCost();
15+
if (checkBalanceClient(client, cost)) {
16+
client.withdraw(cost);
17+
client.addProduct(product);
18+
} else {
19+
client.addCodeError(CodeError.NOT_ENOUGH_FUNDS_BALANCE);
20+
System.out.println("toSell: Failed NOT_ENOUGH_FUNDS_BALANCE");
21+
}
22+
}
23+
24+
/**
25+
* Check paying capacity {@link Client}.
26+
*
27+
* @return false if {@link Client} cant buy {@link Product}.
28+
*/
29+
private boolean checkBalanceClient(Client client, int cost) {
30+
return client.haveAmountOnBalance(cost);
31+
}
32+
33+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
/**
5+
* Need for operations to buy.
6+
* Performs operations over balance.
7+
* If failed operations buy add {@link CodeError} in method {@link Client#addCodeError(CodeError)}.
8+
*/
9+
class Client {
10+
private int balance;
11+
private List<CodeError> codeErrors = new ArrayList<>();
12+
private List<Product> products = new ArrayList<>();
13+
14+
Client(int balance) {
15+
this.balance = balance;
16+
}
17+
18+
boolean haveAmountOnBalance(int amount) {
19+
return (balance >= amount);
20+
}
21+
22+
int getBalance() {
23+
return balance;
24+
}
25+
26+
void withdraw(int amount) {
27+
balance -= amount;
28+
}
29+
30+
void addCodeError(CodeError codeError) {
31+
codeErrors.add(codeError);
32+
}
33+
34+
List<CodeError> getCodeErrors() {
35+
return codeErrors;
36+
}
37+
38+
void addProduct(Product product) {
39+
products.add(product);
40+
}
41+
42+
List<Product> getProducts() {
43+
return products;
44+
}
45+
46+
@Override
47+
public String toString() {
48+
return "Client{" +
49+
"balance=" + balance +
50+
", codeErrors=" + codeErrors +
51+
", products=" + products +
52+
'}';
53+
}
54+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
/**
2+
* This enum for Code Error when buy.
3+
*/
4+
enum CodeError {
5+
NOT_ENOUGH_FUNDS_BALANCE
6+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
3+
/**
4+
* This example to using Mockito for testing code. Example is in CashierTest.
5+
*/
6+
class Main {
7+
public static void main(String[] args) {
8+
sellMilkFailed();
9+
}
10+
11+
/**
12+
* This example {@link Client} to buy {@link Product}
13+
*/
14+
private static void sellMilk() {
15+
Product milk = new Product("Milk",150);
16+
Client client = new Client(300);
17+
Cashier cashier = new Cashier();
18+
19+
System.out.println(client.getProducts()); //[]
20+
cashier.toSell(client,milk);
21+
System.out.println(client.getProducts()); //[Product{name='Milk', cost=150}]
22+
}
23+
24+
/**
25+
* This example {@link Client} can't to buy {@link Product} because not enough funds balance.
26+
*/
27+
private static void sellMilkFailed() {
28+
Product milk = new Product("Milk",150);
29+
Client client = new Client(100);
30+
Cashier cashier = new Cashier();
31+
32+
System.out.println(client.getProducts()); //[]
33+
cashier.toSell(client,milk);
34+
System.out.println(client.getProducts()); //[]
35+
System.out.println(client.getCodeErrors()); //[NOT_ENOUGH_FUNDS_BALANCE]
36+
}
37+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* This thing which sells store.
3+
*/
4+
class Product {
5+
private final String name;
6+
private final int cost;
7+
8+
Product(String name, int cost) {
9+
this.name = name;
10+
this.cost = cost;
11+
}
12+
13+
String getName() {
14+
return name;
15+
}
16+
17+
int getCost() {
18+
return cost;
19+
}
20+
21+
@Override
22+
public String toString() {
23+
return "Product{" +
24+
"name='" + name + '\'' +
25+
", cost=" + cost +
26+
'}';
27+
}
28+
}
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import org.junit.Test;
2+
3+
import static org.mockito.Mockito.*;
4+
5+
/**
6+
* This example about how to test method call using Mockito.
7+
*/
8+
public class CashierTest {
9+
10+
private final static int costMilk = 50;
11+
private Cashier cashier = new Cashier();
12+
/**
13+
* Here we create Mock for testing.
14+
* We test Cashier not Product and Client. That is why we will replace them on Mock.
15+
* For create Mock I use my method {@link CashierTest#createMockMilk()}
16+
* and {@link CashierTest#createMockClient(boolean)}.
17+
* You can create Mock with use Annotation {@link org.mockito.Mock}. Example this {@link CreateMockWithAnnotation}.
18+
*/
19+
private Product milk = createMockMilk();
20+
private Client client = createMockClient(true);
21+
22+
private static Product createMockMilk() {
23+
//So we get mock.
24+
Product milk = mock(Product.class);
25+
//Next, setting mock.
26+
//Here we say when the milk will call getName() then return "Milk".
27+
when(milk.getName()).thenReturn("Milk");
28+
//Here we say when the milk will call getCost() then return value is costMilk.
29+
when(milk.getCost()).thenReturn(costMilk);
30+
return milk;
31+
}
32+
33+
private static Client createMockClient(boolean haveAmountOnBalance) {
34+
Client client = mock(Client.class);
35+
/*
36+
Here we say when the client will call haveAmountOnBalance()
37+
whit param value is costMilk then return value is haveAmountOnBalance.
38+
*/
39+
when(client.haveAmountOnBalance(costMilk)).thenReturn(haveAmountOnBalance);
40+
return client;
41+
}
42+
43+
/**
44+
* Here we to test methods call for {@link Client}.
45+
*/
46+
@Test
47+
public void testToSellCallMethodInClient() throws Exception {
48+
cashier.toSell(client, milk);
49+
50+
/*
51+
Next, we check call methods in client.
52+
Here we say check call method in client haveAmountOnBalance() whit param value is costMilk.
53+
If method not call or call two or more times, test failed.
54+
*/
55+
verify(client).haveAmountOnBalance(costMilk);
56+
verify(client).withdraw(costMilk);
57+
verify(client).addProduct(milk);
58+
}
59+
60+
/**
61+
* This we test method {@link Product#getCost()} to call only.
62+
*/
63+
@SuppressWarnings("ResultOfMethodCallIgnored")
64+
@Test
65+
public void testToSellCallMethodInProduct() throws Exception {
66+
cashier.toSell(client, milk);
67+
/*
68+
Also we cen check how many times use method.
69+
Here we say milk most call only one method getCost(). Otherwise test failed.
70+
*/
71+
verify(milk, only()).getCost();
72+
}
73+
74+
/**
75+
* Here we test behavior if not enough funds balance.
76+
*/
77+
@Test
78+
public void ifNotEnoughFundsBalance() throws Exception {
79+
Client clientPoor = createMockClient(false);
80+
cashier.toSell(clientPoor, milk);
81+
82+
verify(clientPoor).haveAmountOnBalance(costMilk);
83+
verify(clientPoor).addCodeError(CodeError.NOT_ENOUGH_FUNDS_BALANCE);
84+
85+
verify(client, never()).withdraw(costMilk);
86+
verify(client, never()).addProduct(milk);
87+
}
88+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import org.junit.Test;
2+
3+
import java.util.List;
4+
5+
import static org.hamcrest.CoreMatchers.is;
6+
import static org.junit.Assert.*;
7+
8+
public class ClientTest {
9+
10+
private Client client = new Client(100);
11+
12+
@Test
13+
public void testGetBalance() throws Exception {
14+
assertThat(client.getBalance(),is(100));
15+
}
16+
17+
@Test
18+
public void testHaveAmountOnBalance() throws Exception {
19+
assertFalse(client.haveAmountOnBalance(101));
20+
assertTrue(client.haveAmountOnBalance(100));
21+
assertTrue(client.haveAmountOnBalance(99));
22+
}
23+
24+
@Test
25+
public void testWithdraw() throws Exception {
26+
client.withdraw(30);
27+
assertThat(client.getBalance(),is(70));
28+
}
29+
30+
@Test
31+
public void testAddCodeError() throws Exception {
32+
final CodeError error = CodeError.NOT_ENOUGH_FUNDS_BALANCE;
33+
client.addCodeError(error);
34+
List<CodeError> codeErrors = client.getCodeErrors();
35+
assertThat(codeErrors.size(),is(1));
36+
assertThat(codeErrors.get(0),is(error));
37+
}
38+
39+
@Test
40+
public void testAddProduct() throws Exception {
41+
Product milk = new Product("Milk", 50);
42+
client.addProduct(milk);
43+
List<Product> products = client.getProducts();
44+
assertThat(products.size(),is(1));
45+
assertThat(products.get(0),is(milk));
46+
}
47+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import org.junit.Before;
2+
import org.junit.Test;
3+
import org.junit.runner.RunWith;
4+
import org.mockito.Mock;
5+
import org.mockito.runners.MockitoJUnitRunner;
6+
7+
import static org.mockito.Mockito.when;
8+
9+
/**
10+
* This example create Mock with use Annotation.
11+
*/
12+
@RunWith(MockitoJUnitRunner.class)
13+
public class CreateMockWithAnnotation {
14+
15+
private static int costMilk = 10;
16+
@Mock
17+
private Client client;
18+
@Mock
19+
private Product milk;
20+
21+
@Before
22+
public void setUp() throws Exception {
23+
settingMockClient(true);
24+
settingMockMilk();
25+
}
26+
27+
@Test
28+
public void test() throws Exception {
29+
System.out.println(client);
30+
System.out.println(milk);
31+
}
32+
33+
@SuppressWarnings("SameParameterValue")
34+
private void settingMockClient(boolean haveAmountOnBalance) {
35+
when(client.haveAmountOnBalance(costMilk)).thenReturn(haveAmountOnBalance);
36+
}
37+
38+
private void settingMockMilk() {
39+
when(milk.getName()).thenReturn("Milk");
40+
when(milk.getCost()).thenReturn(costMilk);
41+
}
42+
}

0 commit comments

Comments
 (0)