renamed back to testing-modules, pulled together testing-modules-2 modules into single module
This commit is contained in:
13
testing-modules/mockito/.gitignore
vendored
Normal file
13
testing-modules/mockito/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
24
testing-modules/mockito/README.md
Normal file
24
testing-modules/mockito/README.md
Normal file
@@ -0,0 +1,24 @@
|
||||
=========
|
||||
|
||||
## Mockito Cookbooks and Examples
|
||||
|
||||
|
||||
### Relevant Articles:
|
||||
- [Mockito Verify Cookbook](http://www.baeldung.com/mockito-verify)
|
||||
- [Mockito When/Then Cookbook](http://www.baeldung.com/mockito-behavior)
|
||||
- [Mockito – Using Spies](http://www.baeldung.com/mockito-spy)
|
||||
- [Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks](http://www.baeldung.com/mockito-annotations)
|
||||
- [Mockito’s Mock Methods](http://www.baeldung.com/mockito-mock-methods)
|
||||
- [Introduction to PowerMock](http://www.baeldung.com/intro-to-powermock)
|
||||
- [Mocking Exception Throwing using Mockito](http://www.baeldung.com/mockito-exceptions)
|
||||
- [Mocking Void Methods with Mockito](http://www.baeldung.com/mockito-void-methods)
|
||||
- [Mocking of Private Methods Using PowerMock](http://www.baeldung.com/powermock-private-method)
|
||||
- [Mock Final Classes and Methods with Mockito](http://www.baeldung.com/mockito-final)
|
||||
- [Hamcrest Custom Matchers](http://www.baeldung.com/hamcrest-custom-matchers)
|
||||
- [Hamcrest Common Core Matchers](http://www.baeldung.com/hamcrest-core-matchers)
|
||||
- [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks)
|
||||
- [Using Hamcrest Number Matchers](https://www.baeldung.com/hamcrest-number-matchers)
|
||||
- [Quick Guide to BDDMockito](http://www.baeldung.com/bdd-mockito)
|
||||
- [Hamcrest Bean Matchers](http://www.baeldung.com/hamcrest-bean-matchers)
|
||||
- [Hamcrest Object Matchers](http://www.baeldung.com/hamcrest-object-matchers)
|
||||
- [Testing Callbacks with Mockito](http://www.baeldung.com/mockito-callbacks)
|
||||
104
testing-modules/mockito/pom.xml
Normal file
104
testing-modules/mockito/pom.xml
Normal file
@@ -0,0 +1,104 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.baeldung</groupId>
|
||||
<artifactId>mockito</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>mockito</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring-framework.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>${spring-data.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.persistence</groupId>
|
||||
<artifactId>javax.persistence</artifactId>
|
||||
<version>${javax.persistence.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- utils -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-module-junit4</artifactId>
|
||||
<version>${powermock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.powermock</groupId>
|
||||
<artifactId>powermock-api-mockito2</artifactId>
|
||||
<version>${powermock.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>java-hamcrest</artifactId>
|
||||
<version>${hamcrest.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>${spring-boot.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>mockito</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spring-boot.version>2.0.4.RELEASE</spring-boot.version>
|
||||
<spring-framework.version>5.0.8.RELEASE</spring-framework.version>
|
||||
<spring-data.version>2.0.9.RELEASE</spring-data.version>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
|
||||
<!-- testing -->
|
||||
<powermock.version>1.7.0</powermock.version>
|
||||
<hamcrest.version>2.0.0.0</hamcrest.version>
|
||||
<javax.persistence.version>2.1.1</javax.persistence.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,41 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
public class City extends Location {
|
||||
String name;
|
||||
String state;
|
||||
|
||||
public City(String name, String state) {
|
||||
this.name = name;
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setState(String state) {
|
||||
this.state = state;
|
||||
}
|
||||
|
||||
public String getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if (this.name == null && this.state == null) return null;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("[");
|
||||
sb.append("Name: ");
|
||||
sb.append(this.name);
|
||||
sb.append(", ");
|
||||
sb.append("State: ");
|
||||
sb.append(this.state);
|
||||
sb.append("]");
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
public class Location {
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package org.baeldung.hamcrest.custommatchers;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeMatcher;
|
||||
|
||||
public class IsDivisibleBy extends TypeSafeMatcher<Integer> {
|
||||
|
||||
private Integer divider;
|
||||
|
||||
private IsDivisibleBy(Integer divider) {
|
||||
this.divider = divider;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(Integer dividend) {
|
||||
if (divider == 0) return false;
|
||||
return ((dividend % divider) == 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("divisible by " + divider);
|
||||
}
|
||||
|
||||
public static Matcher<Integer> divisibleBy(Integer divider) {
|
||||
return new IsDivisibleBy(divider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package org.baeldung.hamcrest.custommatchers;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeMatcher;
|
||||
|
||||
public class IsOnlyDigits extends TypeSafeMatcher<String> {
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(String s) {
|
||||
try {
|
||||
Integer.parseInt(s);
|
||||
return true;
|
||||
} catch (NumberFormatException nfe) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("only digits");
|
||||
}
|
||||
|
||||
public static Matcher<String> onlyDigits() {
|
||||
return new IsOnlyDigits();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package org.baeldung.hamcrest.custommatchers;
|
||||
|
||||
import org.hamcrest.Description;
|
||||
import org.hamcrest.Matcher;
|
||||
import org.hamcrest.TypeSafeMatcher;
|
||||
|
||||
public class IsUppercase extends TypeSafeMatcher<String> {
|
||||
|
||||
@Override
|
||||
protected boolean matchesSafely(String s) {
|
||||
return s.equals(s.toUpperCase());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void describeTo(Description description) {
|
||||
description.appendText("all uppercase");
|
||||
}
|
||||
|
||||
public static Matcher<String> uppercase() {
|
||||
return new IsUppercase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.baeldung.mockito.service;
|
||||
|
||||
public class ActionHandler {
|
||||
|
||||
private Service service;
|
||||
|
||||
public ActionHandler(Service service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
public void doAction() {
|
||||
service.doAction("our-request", new Callback<Response>() {
|
||||
@Override
|
||||
public void reply(Response response) {
|
||||
handleResponse(response);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void handleResponse(Response response) {
|
||||
if (response.isValid()) {
|
||||
response.setData(new Data("Successful data response"));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package org.baeldung.mockito.service;
|
||||
|
||||
public interface Callback<T> {
|
||||
|
||||
void reply(T response);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package org.baeldung.mockito.service;
|
||||
|
||||
public class Data {
|
||||
|
||||
private String message;
|
||||
|
||||
public Data(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package org.baeldung.mockito.service;
|
||||
|
||||
public class Response {
|
||||
|
||||
private Data data;
|
||||
private boolean isValid = true;
|
||||
|
||||
public boolean isValid() {
|
||||
return isValid;
|
||||
}
|
||||
|
||||
public void setIsValid(boolean isValid) {
|
||||
this.isValid = isValid;
|
||||
}
|
||||
|
||||
public void setData(Data data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public Data getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package org.baeldung.mockito.service;
|
||||
|
||||
public interface Service {
|
||||
|
||||
void doAction(String request, Callback<Response> callback);
|
||||
|
||||
}
|
||||
19
testing-modules/mockito/src/main/resources/logback.xml
Normal file
19
testing-modules/mockito/src/main/resources/logback.xml
Normal file
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.transaction" level="WARN" />
|
||||
|
||||
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
|
||||
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
class CollaboratorForPartialMocking {
|
||||
|
||||
static String staticMethod() {
|
||||
return "Hello Baeldung!";
|
||||
}
|
||||
|
||||
final String finalMethod() {
|
||||
return "Hello Baeldung!";
|
||||
}
|
||||
|
||||
private String privateMethod() {
|
||||
return "Hello Baeldung!";
|
||||
}
|
||||
|
||||
String privateMethodCaller() {
|
||||
return privateMethod() + " Welcome to the Java world.";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
class CollaboratorWithFinalMethods {
|
||||
|
||||
final String helloMethod() {
|
||||
return "Hello World!";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
class CollaboratorWithStaticMethods {
|
||||
|
||||
static String firstMethod(String name) {
|
||||
return "Hello " + name + " !";
|
||||
}
|
||||
|
||||
static String secondMethod() {
|
||||
return "Hello no one!";
|
||||
}
|
||||
|
||||
static String thirdMethod() {
|
||||
return "Hello no one again!";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
class LuckyNumberGenerator {
|
||||
|
||||
public int getLuckyNumber(String name) {
|
||||
|
||||
saveIntoDatabase(name);
|
||||
|
||||
if (name == null) {
|
||||
return getDefaultLuckyNumber();
|
||||
}
|
||||
|
||||
return getComputedLuckyNumber(name.length());
|
||||
}
|
||||
|
||||
private void saveIntoDatabase(String name) {
|
||||
// Save the name into the database
|
||||
}
|
||||
|
||||
private int getDefaultLuckyNumber() {
|
||||
return 100;
|
||||
}
|
||||
|
||||
private int getComputedLuckyNumber(int length) {
|
||||
return length < 5 ? 5 : 10000;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.powermock.api.mockito.PowerMockito.doReturn;
|
||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
||||
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
|
||||
import static org.powermock.api.mockito.PowerMockito.when;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator")
|
||||
public class LuckyNumberGeneratorIntegrationTest {
|
||||
|
||||
@Test
|
||||
public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
|
||||
|
||||
when(mock, "getDefaultLuckyNumber").thenReturn(300);
|
||||
|
||||
int result = mock.getLuckyNumber(null);
|
||||
|
||||
assertEquals(300, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
|
||||
|
||||
doReturn(1).when(mock, "getComputedLuckyNumber", ArgumentMatchers.anyInt());
|
||||
|
||||
int result = mock.getLuckyNumber("Jack");
|
||||
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
|
||||
|
||||
int result = mock.getLuckyNumber("Tyranosorous");
|
||||
|
||||
verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString());
|
||||
assertEquals(10000, result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.powermock.api.mockito.PowerMockito.*;
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.*")
|
||||
public class PowerMockitoIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenFinalMethods_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
CollaboratorWithFinalMethods mock = mock(CollaboratorWithFinalMethods.class);
|
||||
whenNew(CollaboratorWithFinalMethods.class).withNoArguments().thenReturn(mock);
|
||||
|
||||
CollaboratorWithFinalMethods collaborator = new CollaboratorWithFinalMethods();
|
||||
verifyNew(CollaboratorWithFinalMethods.class).withNoArguments();
|
||||
|
||||
when(collaborator.helloMethod()).thenReturn("Hello Baeldung!");
|
||||
String welcome = collaborator.helloMethod();
|
||||
verify(collaborator).helloMethod();
|
||||
assertEquals("Hello Baeldung!", welcome);
|
||||
}
|
||||
|
||||
@Test(expected = RuntimeException.class)
|
||||
public void givenStaticMethods_whenUsingPowerMockito_thenCorrect() {
|
||||
mockStatic(CollaboratorWithStaticMethods.class);
|
||||
|
||||
when(CollaboratorWithStaticMethods.firstMethod(Mockito.anyString())).thenReturn("Hello Baeldung!");
|
||||
when(CollaboratorWithStaticMethods.secondMethod()).thenReturn("Nothing special");
|
||||
doThrow(new RuntimeException()).when(CollaboratorWithStaticMethods.class);
|
||||
CollaboratorWithStaticMethods.thirdMethod();
|
||||
|
||||
String firstWelcome = CollaboratorWithStaticMethods.firstMethod("Whoever");
|
||||
String secondWelcome = CollaboratorWithStaticMethods.firstMethod("Whatever");
|
||||
|
||||
assertEquals("Hello Baeldung!", firstWelcome);
|
||||
assertEquals("Hello Baeldung!", secondWelcome);
|
||||
|
||||
verifyStatic(times(2));
|
||||
CollaboratorWithStaticMethods.firstMethod(Mockito.anyString());
|
||||
|
||||
verifyStatic(Mockito.never());
|
||||
CollaboratorWithStaticMethods.secondMethod();
|
||||
|
||||
CollaboratorWithStaticMethods.thirdMethod();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPartialMocking_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
String returnValue;
|
||||
|
||||
spy(CollaboratorForPartialMocking.class);
|
||||
when(CollaboratorForPartialMocking.staticMethod()).thenReturn("I am a static mock method.");
|
||||
returnValue = CollaboratorForPartialMocking.staticMethod();
|
||||
verifyStatic();
|
||||
CollaboratorForPartialMocking.staticMethod();
|
||||
assertEquals("I am a static mock method.", returnValue);
|
||||
|
||||
CollaboratorForPartialMocking collaborator = new CollaboratorForPartialMocking();
|
||||
CollaboratorForPartialMocking mock = spy(collaborator);
|
||||
|
||||
when(mock.finalMethod()).thenReturn("I am a final mock method.");
|
||||
returnValue = mock.finalMethod();
|
||||
verify(mock,times(3)).finalMethod();
|
||||
assertEquals("I am a final mock method.", returnValue);
|
||||
|
||||
when(mock, "privateMethod").thenReturn("I am a private mock method.");
|
||||
returnValue = mock.privateMethodCaller();
|
||||
verifyPrivate(mock).invoke("privateMethod");
|
||||
assertEquals("I am a private mock method. Welcome to the Java world.", returnValue);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package org.baeldung.bddmockito;
|
||||
|
||||
import static org.junit.Assert.fail;
|
||||
import static org.mockito.BDDMockito.*;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
|
||||
|
||||
public class BDDMockitoIntegrationTest {
|
||||
|
||||
PhoneBookService phoneBookService;
|
||||
PhoneBookRepository phoneBookRepository;
|
||||
|
||||
String momContactName = "Mom";
|
||||
String momPhoneNumber = "01234";
|
||||
String xContactName = "x";
|
||||
String tooLongPhoneNumber = "01111111111111";
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
phoneBookRepository = Mockito.mock(PhoneBookRepository.class);
|
||||
phoneBookService = new PhoneBookService(phoneBookRepository);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidContactName_whenSearchInPhoneBook_thenRetunPhoneNumber() {
|
||||
given(phoneBookRepository.contains(momContactName)).willReturn(true);
|
||||
given(phoneBookRepository.getPhoneNumberByContactName(momContactName))
|
||||
.will((InvocationOnMock invocation) -> {
|
||||
if(invocation.getArgument(0).equals(momContactName)) {
|
||||
return momPhoneNumber;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
String phoneNumber = phoneBookService.search(momContactName);
|
||||
|
||||
then(phoneBookRepository).should().contains(momContactName);
|
||||
then(phoneBookRepository).should().getPhoneNumberByContactName(momContactName);
|
||||
Assert.assertEquals(phoneNumber, momPhoneNumber);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidContactName_whenSearch_thenRetunNull() {
|
||||
given(phoneBookRepository.contains(xContactName)).willReturn(false);
|
||||
|
||||
String phoneNumber = phoneBookService.search(xContactName);
|
||||
|
||||
then(phoneBookRepository).should().contains(xContactName);
|
||||
then(phoneBookRepository).should(never()).getPhoneNumberByContactName(xContactName);
|
||||
Assert.assertEquals(phoneNumber, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValidContactNameAndPhoneNumber_whenRegister_thenSucceed() {
|
||||
given(phoneBookRepository.contains(momContactName)).willReturn(false);
|
||||
|
||||
phoneBookService.register(momContactName, momPhoneNumber);
|
||||
|
||||
verify(phoneBookRepository).insert(momContactName, momPhoneNumber);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenEmptyPhoneNumber_whenRegister_thenFail() {
|
||||
given(phoneBookRepository.contains(momContactName)).willReturn(false);
|
||||
|
||||
phoneBookService.register(xContactName, "");
|
||||
|
||||
then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLongPhoneNumber_whenRegister_thenFail() {
|
||||
given(phoneBookRepository.contains(xContactName)).willReturn(false);
|
||||
willThrow(new RuntimeException())
|
||||
.given(phoneBookRepository).insert(any(String.class), eq(tooLongPhoneNumber));
|
||||
|
||||
try {
|
||||
phoneBookService.register(xContactName, tooLongPhoneNumber);
|
||||
fail("Should throw exception");
|
||||
} catch (RuntimeException ex) { }
|
||||
|
||||
then(phoneBookRepository).should(never()).insert(momContactName, tooLongPhoneNumber);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenExistentContactName_whenRegister_thenFail() {
|
||||
given(phoneBookRepository.contains(momContactName))
|
||||
.willThrow(new RuntimeException("Name already exist"));
|
||||
|
||||
try {
|
||||
phoneBookService.register(momContactName, momPhoneNumber);
|
||||
fail("Should throw exception");
|
||||
} catch(Exception ex) { }
|
||||
|
||||
then(phoneBookRepository).should(never()).insert(momContactName, momPhoneNumber);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package org.baeldung.bddmockito;
|
||||
|
||||
public interface PhoneBookRepository {
|
||||
|
||||
/**
|
||||
* Insert phone record
|
||||
* @param name Contact name
|
||||
* @param phone Phone number
|
||||
*/
|
||||
void insert(String name, String phone);
|
||||
|
||||
/**
|
||||
* Search for contact phone number
|
||||
* @param name Contact name
|
||||
* @return phone number
|
||||
*/
|
||||
String getPhoneNumberByContactName(String name);
|
||||
|
||||
/**
|
||||
* Check if the phonebook contains this contact
|
||||
* @param name Contact name
|
||||
* @return true if this contact name exists
|
||||
*/
|
||||
boolean contains(String name);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package org.baeldung.bddmockito;
|
||||
|
||||
public class PhoneBookService {
|
||||
|
||||
private PhoneBookRepository phoneBookRepository;
|
||||
|
||||
public PhoneBookService(PhoneBookRepository phoneBookRepository) {
|
||||
this.phoneBookRepository = phoneBookRepository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a contact
|
||||
* @param name Contact name
|
||||
* @param phone Phone number
|
||||
*/
|
||||
public void register(String name, String phone) {
|
||||
if(!name.isEmpty() && !phone.isEmpty() && !phoneBookRepository.contains(name)) {
|
||||
phoneBookRepository.insert(name, phone);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a phone number by contact name
|
||||
* @param name Contact name
|
||||
* @return Phone number
|
||||
*/
|
||||
public String search(String name) {
|
||||
if(!name.isEmpty() && phoneBookRepository.contains(name)) {
|
||||
return phoneBookRepository.getPhoneNumberByContactName(name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static java.util.stream.Collectors.toList;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.hasProperty;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.equalToIgnoringCase;
|
||||
import static org.hamcrest.Matchers.samePropertyValuesAs;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.beans.PropertyUtil.getPropertyDescriptor;
|
||||
import static org.hamcrest.beans.PropertyUtil.propertyDescriptorsFor;
|
||||
|
||||
public class HamcrestBeansUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACity_whenHasProperty_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city, hasProperty("name"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenNotHasProperty_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city, not(hasProperty("country")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenHasPropertyWithValueEqualTo_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city, hasProperty("name", equalTo("San Francisco")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenHasPropertyWithValueEqualToIgnoringCase_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city, hasProperty("state", equalToIgnoringCase("ca")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenSamePropertyValuesAs_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
City city2 = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city, samePropertyValuesAs(city2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenNotSamePropertyValuesAs_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
City city2 = new City("Los Angeles", "CA");
|
||||
|
||||
assertThat(city, not(samePropertyValuesAs(city2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenGetPropertyDescriptor_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
PropertyDescriptor descriptor = getPropertyDescriptor("state", city);
|
||||
|
||||
assertThat(descriptor
|
||||
.getReadMethod()
|
||||
.getName(), is(equalTo("getState")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenGetPropertyDescriptorsFor_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
PropertyDescriptor[] descriptors = propertyDescriptorsFor(city, Object.class);
|
||||
List<String> getters = Arrays
|
||||
.stream(descriptors)
|
||||
.map(x -> x
|
||||
.getReadMethod()
|
||||
.getName())
|
||||
.collect(toList());
|
||||
|
||||
assertThat(getters, containsInAnyOrder("getName", "getState"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.core.StringEndsWith.endsWith;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWith;
|
||||
|
||||
public class HamcrestCoreMatchersUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingIsForMatch() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, is("hamcrest core"));
|
||||
assertThat(testString, is(equalTo("hamcrest core")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenDifferentStaticTypeTestInput_WhenUsingEqualToObject_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
Object original = 100;
|
||||
|
||||
// ASSERT
|
||||
assertThat(original, equalToObject(100));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingInstanceOfForClassTypeCheck() {
|
||||
|
||||
assertThat("hamcrest", is(instanceOf(String.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingIsA_ThenAssertType() {
|
||||
|
||||
assertThat("hamcrest core", isA(String.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingEqualToMatcherForEquality() {
|
||||
|
||||
// GIVEN
|
||||
String actualString = "Hamcrest Core";
|
||||
List<String> actualList = Lists.newArrayList("hamcrest", "core");
|
||||
|
||||
// ASSERT
|
||||
assertThat(actualString, is(equalTo("Hamcrest Core")));
|
||||
assertThat(actualList, is(equalTo(Lists.newArrayList("hamcrest", "core"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingNotForMatch() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, not("hamcrest core"));
|
||||
assertThat(testString, is(not(equalTo("hamcrest core"))));
|
||||
assertThat(testString, is(not(instanceOf(Integer.class))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingNullValueForNullCheck() {
|
||||
|
||||
// GIVEN
|
||||
Integer nullObject = null;
|
||||
|
||||
// ASSERT
|
||||
assertThat(nullObject, is(nullValue()));
|
||||
assertThat(nullObject, is(nullValue(Integer.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingNotNullValueForNotNullCheck() {
|
||||
|
||||
// GIVEN
|
||||
Integer testNumber = 123;
|
||||
|
||||
// ASSERT
|
||||
assertThat(testNumber, is(notNullValue()));
|
||||
assertThat(testNumber, is(notNullValue(Integer.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenStartsWith_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, startsWith("hamcrest"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void giveString_WhenStartsWithIgnoringCase_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, startsWithIgnoringCase("HAMCREST"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenEndsWith_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, endsWith("core"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenEndsWithIgnoringCase_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, endsWithIgnoringCase("CORE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenContainsString_ThenCorrect() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, containsString("co"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_WhenContainsStringIgnoringCase_ThenCorrect() {
|
||||
|
||||
|
||||
// GIVEN
|
||||
String testString = "hamcrest core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, containsStringIgnoringCase("CO"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingHasItemInCollection() {
|
||||
|
||||
// GIVEN
|
||||
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
|
||||
|
||||
// ASSERT
|
||||
assertThat(list, hasItem("java"));
|
||||
assertThat(list, hasItem(isA(String.class)));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingHasItemsInCollection() {
|
||||
|
||||
// GIVEN
|
||||
List<String> list = Lists.newArrayList("java", "spring", "baeldung");
|
||||
|
||||
// ASSERT
|
||||
assertThat(list, hasItems("java", "baeldung"));
|
||||
assertThat(list, hasItems(isA(String.class), endsWith("ing")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingAnyForClassType() {
|
||||
|
||||
assertThat("hamcrest", is(any(String.class)));
|
||||
assertThat("hamcrest", is(any(Object.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingAllOfForAllMatchers() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, allOf(startsWith("Ham"), endsWith("ore"), containsString("Core")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingAnyOfForAnyMatcher() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, anyOf(startsWith("Ham"), containsString("baeldung")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingBothForMatcher() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core Matchers";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, both(startsWith("Ham")).and(containsString("Core")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingEitherForMatcher() {
|
||||
|
||||
// GIVEN
|
||||
String testString = "Hamcrest Core Matchers";
|
||||
|
||||
// ASSERT
|
||||
assertThat(testString, either(startsWith("Bael")).or(containsString("Core")));
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void givenTestInput_WhenUsingEveryItemForMatchInCollection() {
|
||||
|
||||
// GIVEN
|
||||
List<String> testItems = Lists.newArrayList("Common", "Core", "Combinable");
|
||||
|
||||
// ASSERT
|
||||
assertThat(testItems, everyItem(startsWith("Co")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoTestInputs_WhenUsingSameInstanceForMatch() {
|
||||
|
||||
// GIVEN
|
||||
String string1 = "hamcrest";
|
||||
String string2 = string1;
|
||||
|
||||
// ASSERT
|
||||
assertThat(string1, is(sameInstance(string2)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoTestInputs_WhenUsingTheInstanceForMatch() {
|
||||
// GIVEN
|
||||
String string1 = "hamcrest";
|
||||
String string2 = string1;
|
||||
|
||||
// ASSERT
|
||||
assertThat(string1, is(theInstance(string2)));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.baeldung.hamcrest.custommatchers.IsDivisibleBy.divisibleBy;
|
||||
import static org.baeldung.hamcrest.custommatchers.IsOnlyDigits.onlyDigits;
|
||||
import static org.baeldung.hamcrest.custommatchers.IsUppercase.uppercase;
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
public class HamcrestCustomUnitTest {
|
||||
|
||||
@Test
|
||||
public final void givenAString_whenIsOnlyDigits_thenCorrect() {
|
||||
String digits = "123";
|
||||
|
||||
assertThat(digits, is(onlyDigits()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAString_whenIsNotOnlyDigits_thenCorrect() {
|
||||
String aphanumeric = "123ABC";
|
||||
|
||||
assertThat(aphanumeric, is(not(onlyDigits())));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAString_whenIsUppercase_thenCorrect() {
|
||||
String uppercaseWord = "HELLO";
|
||||
|
||||
assertThat(uppercaseWord, is(uppercase()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAnEvenInteger_whenDivisibleByTwo_thenCorrect() {
|
||||
Integer ten = 10;
|
||||
Integer two = 2;
|
||||
|
||||
assertThat(ten, is(divisibleBy(two)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenAnOddInteger_whenNotDivisibleByTwo_thenCorrect() {
|
||||
Integer eleven = 11;
|
||||
Integer two = 2;
|
||||
|
||||
assertThat(eleven, is(not(divisibleBy(two))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
import static org.hamcrest.core.StringContains.containsString;
|
||||
import static org.hamcrest.io.FileMatchers.aFileNamed;
|
||||
import static org.hamcrest.io.FileMatchers.aFileWithAbsolutePath;
|
||||
import static org.hamcrest.io.FileMatchers.aFileWithCanonicalPath;
|
||||
import static org.hamcrest.io.FileMatchers.aFileWithSize;
|
||||
import static org.hamcrest.io.FileMatchers.aReadableFile;
|
||||
import static org.hamcrest.io.FileMatchers.aWritableFile;
|
||||
import static org.hamcrest.io.FileMatchers.anExistingDirectory;
|
||||
import static org.hamcrest.io.FileMatchers.anExistingFile;
|
||||
import static org.hamcrest.io.FileMatchers.anExistingFileOrDirectory;
|
||||
import static org.hamcrest.number.OrderingComparison.greaterThan;
|
||||
import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HamcrestFileUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingFileName_thenCorrect() {
|
||||
File file = new File("src/test/resources/test1.in");
|
||||
|
||||
assertThat(file, aFileNamed(equalToIgnoringCase("test1.in")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingFileOrDirExist_thenCorrect() {
|
||||
File file = new File("src/test/resources/test1.in");
|
||||
File dir = new File("src/test/resources");
|
||||
|
||||
assertThat(file, anExistingFile());
|
||||
assertThat(dir, anExistingDirectory());
|
||||
assertThat(file, anExistingFileOrDirectory());
|
||||
assertThat(dir, anExistingFileOrDirectory());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingFileIsReadableAndWritable_thenCorrect() {
|
||||
File file = new File("src/test/resources/test1.in");
|
||||
|
||||
assertThat(file, aReadableFile());
|
||||
assertThat(file, aWritableFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingFileSize_thenCorrect() {
|
||||
File file = new File("src/test/resources/test1.in");
|
||||
|
||||
assertThat(file, aFileWithSize(11));
|
||||
assertThat(file, aFileWithSize(greaterThan(1L)));;
|
||||
}
|
||||
|
||||
/*@Test
|
||||
public final void whenVerifyingFilePath_thenCorrect() {
|
||||
File file = new File("src/test/resources/test1.in");
|
||||
|
||||
assertThat(file, aFileWithCanonicalPath(containsString("src/test/resources")));
|
||||
assertThat(file, aFileWithAbsolutePath(containsString("src/test/resources")));
|
||||
}*/
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.closeTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.greaterThan;
|
||||
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
|
||||
import static org.hamcrest.Matchers.lessThan;
|
||||
import static org.hamcrest.Matchers.lessThanOrEqualTo;
|
||||
import static org.hamcrest.Matchers.comparesEqualTo;
|
||||
import static org.hamcrest.Matchers.notANumber;
|
||||
|
||||
public class HamcrestNumberUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenADouble_whenCloseTo_thenCorrect() {
|
||||
double actual = 1.3;
|
||||
double operand = 1;
|
||||
double error = 0.5;
|
||||
assertThat(actual, is(closeTo(operand, error)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenADouble_whenNotCloseTo_thenCorrect() {
|
||||
double actual = 1.6;
|
||||
double operand = 1;
|
||||
double error = 0.5;
|
||||
assertThat(actual, is(not(closeTo(operand, error))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABigDecimal_whenCloseTo_thenCorrect() {
|
||||
BigDecimal actual = new BigDecimal("1.0003");
|
||||
BigDecimal operand = new BigDecimal("1");
|
||||
BigDecimal error = new BigDecimal("0.0005");
|
||||
assertThat(actual, is(closeTo(operand, error)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenABigDecimal_whenNotCloseTo_thenCorrect() {
|
||||
BigDecimal actual = new BigDecimal("1.0006");
|
||||
BigDecimal operand = new BigDecimal("1");
|
||||
BigDecimal error = new BigDecimal("0.0005");
|
||||
assertThat(actual, is(not(closeTo(operand, error))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given5_whenComparesEqualTo5_thenCorrect() {
|
||||
Integer five = 5;
|
||||
assertThat(five, comparesEqualTo(five));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given5_whenNotComparesEqualTo7_thenCorrect() {
|
||||
Integer seven = 7;
|
||||
Integer five = 5;
|
||||
assertThat(five, not(comparesEqualTo(seven)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given7_whenGreaterThan5_thenCorrect() {
|
||||
Integer seven = 7;
|
||||
Integer five = 5;
|
||||
assertThat(seven, is(greaterThan(five)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given7_whenGreaterThanOrEqualTo5_thenCorrect() {
|
||||
Integer seven = 7;
|
||||
Integer five = 5;
|
||||
assertThat(seven, is(greaterThanOrEqualTo(five)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given5_whenGreaterThanOrEqualTo5_thenCorrect() {
|
||||
Integer five = 5;
|
||||
assertThat(five, is(greaterThanOrEqualTo(five)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given3_whenLessThan5_thenCorrect() {
|
||||
Integer three = 3;
|
||||
Integer five = 5;
|
||||
assertThat(three, is(lessThan(five)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given3_whenLessThanOrEqualTo5_thenCorrect() {
|
||||
Integer three = 3;
|
||||
Integer five = 5;
|
||||
assertThat(three, is(lessThanOrEqualTo(five)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given5_whenLessThanOrEqualTo5_thenCorrect() {
|
||||
Integer five = 5;
|
||||
assertThat(five, is(lessThanOrEqualTo(five)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBenjamin_whenGreaterThanAmanda_thenCorrect() {
|
||||
String amanda = "Amanda";
|
||||
String benjamin = "Benjamin";
|
||||
assertThat(benjamin, is(greaterThan(amanda)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmanda_whenLessThanBenajmin_thenCorrect() {
|
||||
String amanda = "Amanda";
|
||||
String benjamin = "Benjamin";
|
||||
assertThat(amanda, is(lessThan(benjamin)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenGreaterThanYesterday_thenCorrect() {
|
||||
LocalDate today = LocalDate.now();
|
||||
LocalDate yesterday = today.minusDays(1);
|
||||
assertThat(today, is(greaterThan(yesterday)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenToday_whenLessThanTomorrow_thenCorrect() {
|
||||
LocalDate today = LocalDate.now();
|
||||
LocalDate tomorrow = today.plusDays(1);
|
||||
assertThat(today, is(lessThan(tomorrow)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAmanda_whenOlderThanBenjamin_thenCorrect() {
|
||||
Person amanda = new Person("Amanda", 20);
|
||||
Person benjamin = new Person("Benjamin", 18);
|
||||
assertThat(amanda, is(greaterThan(benjamin)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBenjamin_whenYoungerThanAmanda_thenCorrect() {
|
||||
Person amanda = new Person("Amanda", 20);
|
||||
Person benjamin = new Person("Benjamin", 18);
|
||||
assertThat(benjamin, is(lessThan(amanda)));
|
||||
}
|
||||
|
||||
class Person implements Comparable<Person> {
|
||||
String name;
|
||||
int age;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Person o) {
|
||||
if (this.age == o.getAge()) return 0;
|
||||
if (this.age > o.age) return 1;
|
||||
else return -1;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNaN_whenIsNotANumber_thenCorrect() {
|
||||
double zero = 0d;
|
||||
assertThat(zero / zero, is(notANumber()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.hasToString;
|
||||
import static org.hamcrest.Matchers.equalToIgnoringCase;
|
||||
import static org.hamcrest.Matchers.emptyOrNullString;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.typeCompatibleWith;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
|
||||
public class HamcrestObjectUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenACity_whenHasToString_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city, hasToString("[Name: San Francisco, State: CA]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenHasToStringEqualToIgnoringCase_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city, hasToString(equalToIgnoringCase("[NAME: SAN FRANCISCO, STATE: CA]")));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenHasToStringEmptyOrNullString_thenCorrect() {
|
||||
City city = new City(null, null);
|
||||
|
||||
assertThat(city, hasToString(emptyOrNullString()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenTypeCompatibleWithLocation_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city.getClass(), is(typeCompatibleWith(Location.class)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenTypeNotCompatibleWithString_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city.getClass(), is(not(typeCompatibleWith(String.class))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACity_whenTypeCompatibleWithObject_thenCorrect() {
|
||||
City city = new City("San Francisco", "CA");
|
||||
|
||||
assertThat(city.getClass(), is(typeCompatibleWith(Object.class)));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package org.baeldung.hamcrest;
|
||||
|
||||
import static org.hamcrest.core.StringContains.containsString;
|
||||
import static org.hamcrest.core.StringContains.containsStringIgnoringCase;
|
||||
import static org.hamcrest.core.StringEndsWith.endsWith;
|
||||
import static org.hamcrest.core.StringEndsWith.endsWithIgnoringCase;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWith;
|
||||
import static org.hamcrest.core.StringStartsWith.startsWithIgnoringCase;
|
||||
import static org.hamcrest.text.IsBlankString.blankOrNullString;
|
||||
import static org.hamcrest.text.IsBlankString.blankString;
|
||||
import static org.hamcrest.text.IsEmptyString.emptyOrNullString;
|
||||
import static org.hamcrest.text.IsEmptyString.emptyString;
|
||||
import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;
|
||||
import static org.hamcrest.text.IsEqualIgnoringWhiteSpace.equalToIgnoringWhiteSpace;
|
||||
import static org.hamcrest.text.MatchesPattern.matchesPattern;
|
||||
import static org.hamcrest.text.StringContainsInOrder.stringContainsInOrder;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class HamcrestTextUnitTest {
|
||||
|
||||
@Test
|
||||
public final void whenTwoStringsAreEqual_thenCorrect() {
|
||||
String first = "hello";
|
||||
String second = "Hello";
|
||||
|
||||
assertThat(first, equalToIgnoringCase(second));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenTwoStringsAreEqualWithWhiteSpace_thenCorrect() {
|
||||
String first = "hello";
|
||||
String second = " Hello ";
|
||||
|
||||
assertThat(first, equalToIgnoringWhiteSpace(second));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenStringIsBlank_thenCorrect() {
|
||||
String first = " ";
|
||||
String second = null;
|
||||
|
||||
assertThat(first, blankString());
|
||||
assertThat(first, blankOrNullString());
|
||||
assertThat(second, blankOrNullString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenStringIsEmpty_thenCorrect() {
|
||||
String first = "";
|
||||
String second = null;
|
||||
|
||||
assertThat(first, emptyString());
|
||||
assertThat(first, emptyOrNullString());
|
||||
assertThat(second, emptyOrNullString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenStringMatchPattern_thenCorrect() {
|
||||
String first = "hello";
|
||||
|
||||
assertThat(first, matchesPattern("[a-z]+"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyStringContains_thenCorrect() {
|
||||
String first = "hello";
|
||||
|
||||
assertThat(first, containsString("lo"));
|
||||
assertThat(first, containsStringIgnoringCase("EL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyStringContainsInOrder_thenCorrect() {
|
||||
String first = "hello";
|
||||
|
||||
assertThat(first, stringContainsInOrder("e","l","o"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyStringStartsWith_thenCorrect() {
|
||||
String first = "hello";
|
||||
|
||||
assertThat(first, startsWith("he"));
|
||||
assertThat(first, startsWithIgnoringCase("HEL"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyStringEndsWith_thenCorrect() {
|
||||
String first = "hello";
|
||||
|
||||
assertThat(first, endsWith("lo"));
|
||||
assertThat(first, endsWithIgnoringCase("LO"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
public final class FinalList extends MyList {
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class MockFinals {
|
||||
|
||||
@Test
|
||||
public void whenMockFinalClassMockWorks() {
|
||||
|
||||
FinalList finalList = new FinalList();
|
||||
|
||||
FinalList mock = mock(FinalList.class);
|
||||
when(mock.size()).thenReturn(2);
|
||||
|
||||
assertNotEquals(mock.size(), finalList.size());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMockFinalMethodMockWorks() {
|
||||
|
||||
MyList myList = new MyList();
|
||||
|
||||
MyList mock = mock(MyList.class);
|
||||
when(mock.finalMethod()).thenReturn(1);
|
||||
|
||||
assertNotEquals(mock.finalMethod(), myList.finalMethod());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
//@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoAnnotationIntegrationTest {
|
||||
|
||||
@Mock
|
||||
private List<String> mockedList;
|
||||
|
||||
@Spy
|
||||
private List<String> spiedList = new ArrayList<>();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public void whenNotUseMockAnnotation_thenCorrect() {
|
||||
final List<String> mockList = Mockito.mock(List.class);
|
||||
mockList.add("one");
|
||||
Mockito.verify(mockList).add("one");
|
||||
assertEquals(0, mockList.size());
|
||||
|
||||
Mockito.when(mockList.size()).thenReturn(100);
|
||||
assertEquals(100, mockList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseMockAnnotation_thenMockIsInjected() {
|
||||
mockedList.add("one");
|
||||
Mockito.verify(mockedList).add("one");
|
||||
assertEquals(0, mockedList.size());
|
||||
|
||||
Mockito.when(mockedList.size()).thenReturn(100);
|
||||
assertEquals(100, mockedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotUseSpyAnnotation_thenCorrect() {
|
||||
final List<String> spyList = Mockito.spy(new ArrayList<String>());
|
||||
spyList.add("one");
|
||||
spyList.add("two");
|
||||
|
||||
Mockito.verify(spyList).add("one");
|
||||
Mockito.verify(spyList).add("two");
|
||||
|
||||
assertEquals(2, spyList.size());
|
||||
|
||||
Mockito.doReturn(100).when(spyList).size();
|
||||
assertEquals(100, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
|
||||
spiedList.add("one");
|
||||
spiedList.add("two");
|
||||
|
||||
Mockito.verify(spiedList).add("one");
|
||||
Mockito.verify(spiedList).add("two");
|
||||
|
||||
assertEquals(2, spiedList.size());
|
||||
|
||||
Mockito.doReturn(100).when(spiedList).size();
|
||||
assertEquals(100, spiedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotUseCaptorAnnotation_thenCorrect() {
|
||||
final List<String> mockList = Mockito.mock(List.class);
|
||||
final ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
|
||||
mockList.add("one");
|
||||
Mockito.verify(mockList).add(arg.capture());
|
||||
|
||||
assertEquals("one", arg.getValue());
|
||||
}
|
||||
|
||||
@Captor
|
||||
private
|
||||
ArgumentCaptor<String> argCaptor;
|
||||
|
||||
@Test
|
||||
public void whenUseCaptorAnnotation_thenTheSam() {
|
||||
mockedList.add("one");
|
||||
Mockito.verify(mockedList).add(argCaptor.capture());
|
||||
|
||||
assertEquals("one", argCaptor.getValue());
|
||||
}
|
||||
|
||||
@Mock
|
||||
private Map<String, String> wordMap;
|
||||
|
||||
@InjectMocks
|
||||
private MyDictionary dic = new MyDictionary();
|
||||
|
||||
@Test
|
||||
public void whenUseInjectMocksAnnotation_thenCorrect() {
|
||||
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
|
||||
|
||||
assertEquals("aMeaning", dic.getMeaning("aWord"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Matchers.anyInt;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class MockitoConfigExamplesIntegrationTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void whenMockReturnBehaviorIsConfigured_thenBehaviorIsVerified() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
|
||||
final boolean added = listMock.add(randomAlphabetic(6));
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenMockReturnBehaviorIsConfigured2_thenBehaviorIsVerified() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
doReturn(false).when(listMock).add(anyString());
|
||||
|
||||
final boolean added = listMock.add(randomAlphabetic(6));
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public final void givenMethodIsConfiguredToThrowException_whenCallingMethod_thenExceptionIsThrown() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenThrow(IllegalStateException.class);
|
||||
|
||||
listMock.add(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public final void whenMethodHasNoReturnType_whenConfiguringBehaviorOfMethod_thenPossible() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
doThrow(NullPointerException.class).when(listMock).clear();
|
||||
|
||||
listMock.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingOnlyOnce_thenNoExceptionIsThrown() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
|
||||
|
||||
listMock.add(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public final void givenBehaviorIsConfiguredToThrowExceptionOnSecondCall_whenCallingTwice_thenExceptionIsThrown() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false).thenThrow(IllegalStateException.class);
|
||||
|
||||
listMock.add(randomAlphabetic(6));
|
||||
listMock.add(randomAlphabetic(6));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
when(listMock.size()).thenCallRealMethod();
|
||||
|
||||
assertThat(listMock.size(), equalTo(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
|
||||
final MyList listMock = Mockito.mock(MyList.class);
|
||||
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
|
||||
|
||||
final String element = listMock.get(1);
|
||||
assertThat(element, is(equalTo("Always the same")));
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public final void givenSpy_whenConfiguringBehaviorOfSpy_thenCorrectlyConfigured() {
|
||||
final MyList instance = new MyList();
|
||||
final MyList spy = Mockito.spy(instance);
|
||||
|
||||
doThrow(NullPointerException.class).when(spy).size();
|
||||
spy.size();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
public class MockitoExceptionIntegrationTest {
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
|
||||
MyDictionary dictMock = mock(MyDictionary.class);
|
||||
when(dictMock.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
||||
|
||||
dictMock.getMeaning("word");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void whenConfigVoidRetunMethodToThrowEx_thenExIsThrown() {
|
||||
MyDictionary dictMock = mock(MyDictionary.class);
|
||||
doThrow(IllegalStateException.class).when(dictMock)
|
||||
.add(anyString(), anyString());
|
||||
|
||||
dictMock.add("word", "meaning");
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenConfigNonVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
|
||||
MyDictionary dictMock = mock(MyDictionary.class);
|
||||
when(dictMock.getMeaning(anyString())).thenThrow(new NullPointerException("Error occurred"));
|
||||
|
||||
dictMock.getMeaning("word");
|
||||
}
|
||||
|
||||
@Test(expected = IllegalStateException.class)
|
||||
public void whenConfigVoidRetunMethodToThrowExWithNewExObj_thenExIsThrown() {
|
||||
MyDictionary dictMock = mock(MyDictionary.class);
|
||||
doThrow(new IllegalStateException("Error occurred")).when(dictMock)
|
||||
.add(anyString(), anyString());
|
||||
|
||||
dictMock.add("word", "meaning");
|
||||
}
|
||||
|
||||
// =====
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void givenSpy_whenConfigNonVoidRetunMethodToThrowEx_thenExIsThrown() {
|
||||
MyDictionary dict = new MyDictionary();
|
||||
MyDictionary spy = Mockito.spy(dict);
|
||||
|
||||
when(spy.getMeaning(anyString())).thenThrow(NullPointerException.class);
|
||||
spy.getMeaning("word");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoInjectIntoSpyUnitTest {
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
spyDic = Mockito.spy(new MyDictionary(wordMap));
|
||||
}
|
||||
|
||||
@Mock
|
||||
private Map<String, String> wordMap;
|
||||
|
||||
@InjectMocks
|
||||
private MyDictionary dic = new MyDictionary();
|
||||
|
||||
private MyDictionary spyDic;
|
||||
|
||||
@Test
|
||||
public void whenUseInjectMocksAnnotation_thenCorrect() {
|
||||
Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
|
||||
|
||||
assertEquals("aMeaning", spyDic.getMeaning("aWord"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.Rule;
|
||||
import org.junit.rules.ExpectedException;
|
||||
import org.mockito.MockSettings;
|
||||
import org.mockito.exceptions.verification.TooLittleActualInvocations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
public class MockitoMockIntegrationTest {
|
||||
|
||||
private static class CustomAnswer implements Answer<Boolean> {
|
||||
@Override
|
||||
public Boolean answer(InvocationOnMock invocation) throws Throwable {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Rule
|
||||
public ExpectedException thrown = ExpectedException.none();
|
||||
|
||||
@Test
|
||||
public void whenUsingSimpleMock_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class);
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithName_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, "myMock");
|
||||
when(listMock.add(anyString())).thenReturn(false);
|
||||
listMock.add(randomAlphabetic(6));
|
||||
|
||||
thrown.expect(TooLittleActualInvocations.class);
|
||||
thrown.expectMessage(containsString("myMock.add"));
|
||||
|
||||
verify(listMock, times(2)).add(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithAnswer_thenCorrect() {
|
||||
MyList listMock = mock(MyList.class, new CustomAnswer());
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingMockWithSettings_thenCorrect() {
|
||||
MockSettings customSettings = withSettings().defaultAnswer(new CustomAnswer());
|
||||
MyList listMock = mock(MyList.class, customSettings);
|
||||
boolean added = listMock.add(randomAlphabetic(6));
|
||||
|
||||
verify(listMock).add(anyString());
|
||||
assertThat(added, is(false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoSpyIntegrationTest {
|
||||
|
||||
@Spy
|
||||
private List<String> aSpyList = new ArrayList<String>();
|
||||
|
||||
@Test
|
||||
public void whenSpyingOnList_thenCorrect() {
|
||||
final List<String> list = new ArrayList<String>();
|
||||
final List<String> spyList = Mockito.spy(list);
|
||||
|
||||
spyList.add("one");
|
||||
spyList.add("two");
|
||||
|
||||
Mockito.verify(spyList).add("one");
|
||||
Mockito.verify(spyList).add("two");
|
||||
|
||||
assertEquals(2, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
|
||||
aSpyList.add("one");
|
||||
aSpyList.add("two");
|
||||
|
||||
Mockito.verify(aSpyList).add("one");
|
||||
Mockito.verify(aSpyList).add("two");
|
||||
|
||||
assertEquals(2, aSpyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStubASpy_thenStubbed() {
|
||||
final List<String> list = new ArrayList<String>();
|
||||
final List<String> spyList = Mockito.spy(list);
|
||||
|
||||
assertEquals(0, spyList.size());
|
||||
|
||||
Mockito.doReturn(100).when(spyList).size();
|
||||
assertEquals(100, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateMock_thenCreated() {
|
||||
final List<String> mockedList = Mockito.mock(ArrayList.class);
|
||||
|
||||
mockedList.add("one");
|
||||
Mockito.verify(mockedList).add("one");
|
||||
|
||||
assertEquals(0, mockedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateSpy_thenCreate() {
|
||||
final List<String> spyList = Mockito.spy(new ArrayList<String>());
|
||||
|
||||
spyList.add("one");
|
||||
Mockito.verify(spyList).add("one");
|
||||
|
||||
assertEquals(1, spyList.size());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.exceptions.verification.NoInteractionsWanted;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.hamcrest.Matchers.hasItem;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.mockito.Matchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
public class MockitoVerifyExamplesIntegrationTest {
|
||||
|
||||
// tests
|
||||
|
||||
@Test
|
||||
public final void givenInteractionWithMockOccurred_whenVerifyingInteraction_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
verify(mockedList).size();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenOneInteractionWithMockOccurred_whenVerifyingNumberOfInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
verify(mockedList, times(1)).size();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNoInteractionWithMockOccurred_whenVerifyingInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
verifyZeroInteractions(mockedList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenNoInteractionWithMethodOfMockOccurred_whenVerifyingInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
verify(mockedList, times(0)).size();
|
||||
}
|
||||
|
||||
@Test(expected = NoInteractionsWanted.class)
|
||||
public final void givenUnverifiedInteraction_whenVerifyingNoUnexpectedInteractions_thenFail() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
mockedList.clear();
|
||||
|
||||
verify(mockedList).size();
|
||||
verifyNoMoreInteractions(mockedList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingOrderOfInteractions_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
mockedList.add("a parameter");
|
||||
mockedList.clear();
|
||||
|
||||
final InOrder inOrder = Mockito.inOrder(mockedList);
|
||||
inOrder.verify(mockedList).size();
|
||||
inOrder.verify(mockedList).add("a parameter");
|
||||
inOrder.verify(mockedList).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionHasNotOccurred_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.size();
|
||||
|
||||
verify(mockedList, never()).clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionHasOccurredAtLeastOnce_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.clear();
|
||||
mockedList.clear();
|
||||
mockedList.clear();
|
||||
|
||||
verify(mockedList, atLeast(1)).clear();
|
||||
verify(mockedList, atMost(10)).clear();
|
||||
}
|
||||
|
||||
// with arguments
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionWithExactArgument_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.add("test");
|
||||
|
||||
verify(mockedList).add("test");
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionWithAnyArgument_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.add("test");
|
||||
|
||||
verify(mockedList).add(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void whenVerifyingAnInteractionWithArgumentCapture_thenCorrect() {
|
||||
final List<String> mockedList = mock(MyList.class);
|
||||
mockedList.addAll(Lists.<String>newArrayList("someElement"));
|
||||
final ArgumentCaptor<List> argumentCaptor = ArgumentCaptor.forClass(List.class);
|
||||
verify(mockedList).addAll(argumentCaptor.capture());
|
||||
final List<String> capturedArgument = argumentCaptor.<List<String>>getValue();
|
||||
assertThat(capturedArgument, hasItem("someElement"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.isA;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoVoidMethodsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenAddCalledVerified() {
|
||||
MyList mockVoid = mock(MyList.class);
|
||||
mockVoid.add(0, "");
|
||||
verify(mockVoid, times(1)).add(0, "");
|
||||
}
|
||||
|
||||
@Test(expected = Exception.class)
|
||||
public void givenNull_addThrows() {
|
||||
MyList mockVoid = mock(MyList.class);
|
||||
doThrow().when(mockVoid).add(isA(Integer.class), isNull());
|
||||
mockVoid.add(0, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddCalledValueCaptured() {
|
||||
MyList mockVoid = mock(MyList.class);
|
||||
ArgumentCaptor<String> valueCapture = ArgumentCaptor.forClass(String.class);
|
||||
doNothing().when(mockVoid).add(any(Integer.class), valueCapture.capture());
|
||||
mockVoid.add(0, "captured");
|
||||
assertEquals("captured", valueCapture.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddCalledAnswered() {
|
||||
MyList mockVoid = mock(MyList.class);
|
||||
doAnswer((Answer<Void>) invocation -> {
|
||||
Object arg0 = invocation.getArgument(0);
|
||||
Object arg1 = invocation.getArgument(1);
|
||||
|
||||
//do something with the arguments here
|
||||
assertEquals(3, arg0);
|
||||
assertEquals("answer me", arg1);
|
||||
|
||||
return null;
|
||||
}).when(mockVoid).add(any(Integer.class), any(String.class));
|
||||
mockVoid.add(3, "answer me");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddCalledRealMethodCalled() {
|
||||
MyList mockVoid = mock(MyList.class);
|
||||
doCallRealMethod().when(mockVoid).add(any(Integer.class), any(String.class));
|
||||
mockVoid.add(1, "real");
|
||||
verify(mockVoid, times(1)).add(1, "real");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
class MyDictionary {
|
||||
|
||||
private Map<String, String> wordMap;
|
||||
|
||||
MyDictionary() {
|
||||
wordMap = new HashMap<>();
|
||||
}
|
||||
|
||||
MyDictionary(Map<String, String> wordMap) {
|
||||
this.wordMap = wordMap;
|
||||
}
|
||||
|
||||
public void add(final String word, final String meaning) {
|
||||
wordMap.put(word, meaning);
|
||||
}
|
||||
|
||||
String getMeaning(final String word) {
|
||||
return wordMap.get(word);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package org.baeldung.mockito;
|
||||
|
||||
import java.util.AbstractList;
|
||||
|
||||
class MyList extends AbstractList<String> {
|
||||
|
||||
@Override
|
||||
public String get(final int index) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
return 1;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void add(int index, String element) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
final public int finalMethod() {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.baeldung.mockito.misusing;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.containsString;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.exceptions.misusing.NotAMockException;
|
||||
import org.mockito.internal.progress.ThreadSafeMockingProgress;
|
||||
|
||||
public class MockitoMisusingUnitTest {
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
ThreadSafeMockingProgress.mockingProgress().reset();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNotASpy_whenDoReturn_thenThrowNotAMock() {
|
||||
try {
|
||||
List<String> list = new ArrayList<String>();
|
||||
|
||||
Mockito.doReturn(100, Mockito.withSettings().lenient())
|
||||
.when(list)
|
||||
.size();
|
||||
|
||||
fail("Should have thrown a NotAMockException because 'list' is not a mock!");
|
||||
} catch (NotAMockException e) {
|
||||
assertThat(e.getMessage(), containsString("Argument passed to when() is not a mock!"));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package org.baeldung.mockito.service;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
public class ActionHandlerUnitTest {
|
||||
|
||||
@Mock
|
||||
private Service service;
|
||||
|
||||
@Captor
|
||||
private ArgumentCaptor<Callback<Response>> callbackCaptor;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServiceWithValidResponse_whenCallbackReceived_thenProcessed() {
|
||||
ActionHandler handler = new ActionHandler(service);
|
||||
handler.doAction();
|
||||
|
||||
verify(service).doAction(anyString(), callbackCaptor.capture());
|
||||
|
||||
Callback<Response> callback = callbackCaptor.getValue();
|
||||
Response response = new Response();
|
||||
callback.reply(response);
|
||||
|
||||
String expectedMessage = "Successful data response";
|
||||
Data data = response.getData();
|
||||
assertEquals("Should receive a successful message: ", expectedMessage, data.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenServiceWithInvalidResponse_whenCallbackReceived_thenNotProcessed() {
|
||||
Response response = new Response();
|
||||
response.setIsValid(false);
|
||||
|
||||
doAnswer((Answer<Void>) invocation -> {
|
||||
Callback<Response> callback = invocation.getArgument(1);
|
||||
callback.reply(response);
|
||||
|
||||
Data data = response.getData();
|
||||
assertNull("No data in invalid response: ", data);
|
||||
return null;
|
||||
}).when(service)
|
||||
.doAction(anyString(), any(Callback.class));
|
||||
|
||||
ActionHandler handler = new ActionHandler(service);
|
||||
handler.doAction();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
mock-maker-inline
|
||||
1
testing-modules/mockito/src/test/resources/test1.in
Normal file
1
testing-modules/mockito/src/test/resources/test1.in
Normal file
@@ -0,0 +1 @@
|
||||
Hello world
|
||||
Reference in New Issue
Block a user