Merge pull request #7689 from sjmillington/testing-libraries

[BAEL-16669] moved testing-modules/testing modules into relevant folders
This commit is contained in:
Loredana Crusoveanu
2019-09-08 15:12:10 +03:00
committed by GitHub
99 changed files with 1530 additions and 1949 deletions

View File

@@ -1,136 +1,136 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>gatling</artifactId>
<version>1.0-SNAPSHOT</version>
<name>gatling</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<args>
<!--<arg>-Ybackend:GenBCode</arg> -->
<arg>-Ydelambdafy:method</arg>
<arg>-target:jvm-1.8</arg>
<arg>-deprecation</arg>
<arg>-feature</arg>
<arg>-unchecked</arg>
<arg>-language:implicitConversions</arg>
<arg>-language:postfixOps</arg>
</args>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>simulation</id>
<build>
<plugins>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling-maven-plugin.version}</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<disableCompiler>true</disableCompiler>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<encoding>UTF-8</encoding>
<scala.version>2.12.6</scala.version> <!--2.11.12 --> <!--2.12.6 -->
<gatling.version>2.3.1</gatling.version> <!--2.2.5 --> <!--2.3.1 -->
<scala-maven-plugin.version>3.2.2</scala-maven-plugin.version> <!--3.2.2 --> <!--3.3.2 -->
<gatling-maven-plugin.version>2.2.4</gatling-maven-plugin.version> <!--2.2.1 --> <!--2.2.4 -->
</properties>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<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>gatling</artifactId>
<version>1.0-SNAPSHOT</version>
<name>gatling</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
<version>${gatling.version}</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.gatling.highcharts</groupId>
<artifactId>gatling-charts-highcharts</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-app</artifactId>
</dependency>
<dependency>
<groupId>io.gatling</groupId>
<artifactId>gatling-recorder</artifactId>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
</dependency>
</dependencies>
<build>
<testSourceDirectory>src/test/scala</testSourceDirectory>
<pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin.version}</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<args>
<!--<arg>-Ybackend:GenBCode</arg> -->
<arg>-Ydelambdafy:method</arg>
<arg>-target:jvm-1.8</arg>
<arg>-deprecation</arg>
<arg>-feature</arg>
<arg>-unchecked</arg>
<arg>-language:implicitConversions</arg>
<arg>-language:postfixOps</arg>
</args>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>simulation</id>
<build>
<plugins>
<plugin>
<groupId>io.gatling</groupId>
<artifactId>gatling-maven-plugin</artifactId>
<version>${gatling-maven-plugin.version}</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>execute</goal>
</goals>
<configuration>
<disableCompiler>true</disableCompiler>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<encoding>UTF-8</encoding>
<scala.version>2.12.6</scala.version> <!--2.11.12 --> <!--2.12.6 -->
<gatling.version>2.3.1</gatling.version> <!--2.2.5 --> <!--2.3.1 -->
<scala-maven-plugin.version>3.2.2</scala-maven-plugin.version> <!--3.2.2 --> <!--3.3.2 -->
<gatling-maven-plugin.version>2.2.4</gatling-maven-plugin.version> <!--2.2.1 --> <!--2.2.4 -->
</properties>
</project>

View File

@@ -1,13 +1,13 @@
import io.gatling.app.Gatling
import io.gatling.core.config.GatlingPropertiesBuilder
object Engine extends App {
val props = new GatlingPropertiesBuilder
props.dataDirectory(IDEPathHelper.dataDirectory.toString)
props.resultsDirectory(IDEPathHelper.resultsDirectory.toString)
props.bodiesDirectory(IDEPathHelper.bodiesDirectory.toString)
props.binariesDirectory(IDEPathHelper.mavenBinariesDirectory.toString)
Gatling.fromMap(props.build)
}
import io.gatling.app.Gatling
import io.gatling.core.config.GatlingPropertiesBuilder
object Engine extends App {
val props = new GatlingPropertiesBuilder
props.dataDirectory(IDEPathHelper.dataDirectory.toString)
props.resultsDirectory(IDEPathHelper.resultsDirectory.toString)
props.bodiesDirectory(IDEPathHelper.bodiesDirectory.toString)
props.binariesDirectory(IDEPathHelper.mavenBinariesDirectory.toString)
Gatling.fromMap(props.build)
}

View File

@@ -1,22 +1,22 @@
import java.nio.file.Path
import io.gatling.commons.util.PathHelper._
object IDEPathHelper {
val gatlingConfUrl: Path = getClass.getClassLoader.getResource("gatling.conf").toURI
val projectRootDir = gatlingConfUrl.ancestor(3)
val mavenSourcesDirectory = projectRootDir / "src" / "test" / "scala"
val mavenResourcesDirectory = projectRootDir / "src" / "test" / "resources"
val mavenTargetDirectory = projectRootDir / "target"
val mavenBinariesDirectory = mavenTargetDirectory / "test-classes"
val dataDirectory = mavenResourcesDirectory / "data"
val bodiesDirectory = mavenResourcesDirectory / "bodies"
val recorderOutputDirectory = mavenSourcesDirectory
val resultsDirectory = mavenTargetDirectory / "gatling"
val recorderConfigFile = mavenResourcesDirectory / "recorder.conf"
}
import java.nio.file.Path
import io.gatling.commons.util.PathHelper._
object IDEPathHelper {
val gatlingConfUrl: Path = getClass.getClassLoader.getResource("gatling.conf").toURI
val projectRootDir = gatlingConfUrl.ancestor(3)
val mavenSourcesDirectory = projectRootDir / "src" / "test" / "scala"
val mavenResourcesDirectory = projectRootDir / "src" / "test" / "resources"
val mavenTargetDirectory = projectRootDir / "target"
val mavenBinariesDirectory = mavenTargetDirectory / "test-classes"
val dataDirectory = mavenResourcesDirectory / "data"
val bodiesDirectory = mavenResourcesDirectory / "bodies"
val recorderOutputDirectory = mavenSourcesDirectory
val resultsDirectory = mavenTargetDirectory / "gatling"
val recorderConfigFile = mavenResourcesDirectory / "recorder.conf"
}

View File

@@ -1,12 +1,12 @@
import io.gatling.recorder.GatlingRecorder
import io.gatling.recorder.config.RecorderPropertiesBuilder
object Recorder extends App {
val props = new RecorderPropertiesBuilder
props.simulationOutputFolder(IDEPathHelper.recorderOutputDirectory.toString)
props.simulationPackage("org.baeldung")
props.bodiesFolder(IDEPathHelper.bodiesDirectory.toString)
GatlingRecorder.fromMap(props.build, Some(IDEPathHelper.recorderConfigFile))
}
import io.gatling.recorder.GatlingRecorder
import io.gatling.recorder.config.RecorderPropertiesBuilder
object Recorder extends App {
val props = new RecorderPropertiesBuilder
props.simulationOutputFolder(IDEPathHelper.recorderOutputDirectory.toString)
props.simulationPackage("org.baeldung")
props.bodiesFolder(IDEPathHelper.bodiesDirectory.toString)
GatlingRecorder.fromMap(props.build, Some(IDEPathHelper.recorderConfigFile))
}

View File

@@ -1,402 +0,0 @@
loadLogFile([{
"package": "mocks",
"name": "ExampleSpockTest",
"start": 1553898111660,
"features": [
{
"name": "should calculate character occurrences in given string",
"start": 1553898111662,
"end": 1553898111699,
"result": "passed",
"attachments": [
]
}
],
"end": 1553898111709,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "mocks",
"name": "ItemServiceTest",
"start": 1553898111714,
"features": [
{
"name": "should spy on EventPublisher method call",
"start": 1553898111714,
"output": [
"I've published: item-id\n"
],
"end": 1553898112250,
"result": "passed",
"attachments": [
]
},
{
"name": "should return items",
"start": 1553898112250,
"end": 1553898112260,
"result": "passed",
"attachments": [
]
},
{
"name": "should publish events about new non-empty saved offers",
"start": 1553898112260,
"end": 1553898112267,
"result": "passed",
"attachments": [
]
},
{
"name": "should return different items for different ids lists",
"start": 1553898112267,
"end": 1553898112280,
"result": "passed",
"attachments": [
]
},
{
"name": "should throw ExternalItemProviderException when ItemProvider fails",
"start": 1553898112281,
"end": 1553898112294,
"result": "passed",
"attachments": [
]
},
{
"name": "should return different items on subsequent call",
"start": 1553898112294,
"narrative": "When method is called for the first time\nThen empty list is returned\nWhen method is called for the second time\nThen item with id=1 is returned\nWhen method is called for the thirdtime\nThen item with id=2 is returned",
"end": 1553898112298,
"result": "passed",
"attachments": [
]
},
{
"name": "should return items sorted by name",
"start": 1553898112299,
"end": 1553898112307,
"result": "passed",
"attachments": [
]
}
],
"end": 1553898112310,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "FirstSpecification",
"name": "FirstSpecification",
"start": 1553898112314,
"features": [
{
"name": "Should verify notify was called",
"start": 1553898112314,
"end": 1553898112324,
"result": "passed",
"attachments": [
]
},
{
"name": "Should return true value for mock",
"start": 1553898112325,
"end": 1553898112344,
"result": "passed",
"attachments": [
]
},
{
"name": "Should return default value for mock",
"start": 1553898112344,
"end": 1553898112347,
"result": "passed",
"attachments": [
]
},
{
"name": "numbers to the power of two",
"start": 1553898112347,
"end": 1553898112358,
"result": "passed",
"attachments": [
]
},
{
"name": "Should get an index out of bounds when removing a non-existent item",
"start": 1553898112358,
"end": 1553898112364,
"result": "passed",
"attachments": [
]
},
{
"name": "Should be able to remove from list",
"start": 1553898112364,
"end": 1553898112366,
"result": "passed",
"attachments": [
]
},
{
"name": "two plus two should equal four",
"start": 1553898112366,
"end": 1553898112368,
"result": "passed",
"attachments": [
]
},
{
"name": "one plus one should equal two",
"start": 1553898112368,
"end": 1553898112391,
"result": "passed",
"attachments": [
]
}
],
"end": 1553898112394,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "IgnoreTest",
"start": 1553898112395,
"end": 1553898112395,
"result": "skipped"
}])
loadLogFile([{
"package": "extensions",
"name": "RetryTest",
"start": 1553898112403,
"end": 1553898112405,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "This title is easy to read for humans",
"start": 1553898112407,
"end": 1553898112408,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "SeeTest",
"start": 1553898112409,
"end": 1553898112411,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "StepwiseTest",
"start": 1553898112422,
"end": 1553898112423,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "NarrativeDescriptionTest",
"start": 1553898112427,
"narrative": "as a user\n i want to save favourite items \n and then get the list of them",
"end": 1553898112433,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "SubjectTest",
"start": 1553898112434,
"end": 1553898112436,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "IgnoreRestTest",
"start": 1553898112437,
"end": 1553898112437,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "StackTraceTest",
"start": 1553898112438,
"features": [
{
"name": "stacktrace",
"start": 1553898112438,
"exceptions": [
"java.lang.RuntimeException: blabla\n\tat extensions.StackTraceTest.stacktrace(StackTraceTest.groovy:10)\n"
],
"end": 1553898112455,
"result": "failed",
"attachments": [
]
}
],
"end": 1553898112470,
"result": "failed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "IgnoreIfTest",
"start": 1553898112471,
"end": 1553898112472,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "RequiresTest",
"start": 1553898112473,
"features": [
{
"name": "I will run only on Windows",
"start": 1553898112474,
"end": 1553898112474,
"result": "skipped"
}
],
"end": 1553898112476,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "IssueTest",
"start": 1553898112477,
"features": [
{
"name": "I'm using Spock configuration file",
"start": 1553898112477,
"tags": [
{
"name": "Bug LO-1000",
"key": "issue",
"value": "LO-1000",
"url": "http:\/\/jira.org\/issues\/LO-1000"
}
],
"end": 1553898112489,
"result": "passed",
"attachments": [
]
}
],
"end": 1553898112490,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "TimeoutTest",
"start": 1553898112491,
"features": [
{
"name": "I will fail after 200 millis",
"start": 1553898112491,
"end": 1553898112514,
"result": "passed",
"attachments": [
]
}
],
"end": 1553898112517,
"result": "passed",
"attachments": [
]
}])
loadLogFile([{
"package": "extensions",
"name": "RestoreSystemPropertiesTest",
"start": 1553898112518,
"features": [
{
"name": "all environment variables will be saved before execution and restored after tests",
"start": 1553898112518,
"end": 1553898112532,
"result": "passed",
"attachments": [
]
}
],
"end": 1553898112539,
"result": "passed",
"attachments": [
]
}])

View File

@@ -15,4 +15,17 @@
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>${jUnitParams.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jUnitParams.version>1.1.0</jUnitParams.version>
</properties>
</project>

View File

@@ -1,126 +1,126 @@
package com.baeldung.junit5.mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import com.baeldung.junit5.mockito.repository.MailClient;
import com.baeldung.junit5.mockito.repository.SettingRepository;
import com.baeldung.junit5.mockito.repository.UserRepository;
import com.baeldung.junit5.mockito.service.DefaultUserService;
import com.baeldung.junit5.mockito.service.Errors;
import com.baeldung.junit5.mockito.service.UserService;
@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class UserServiceUnitTest {
UserService userService;
SettingRepository settingRepository;
@Mock UserRepository userRepository;
@Mock MailClient mailClient;
User user;
@BeforeEach
void init(@Mock SettingRepository settingRepository) {
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
when(settingRepository.getUserNameMinLength()).thenReturn(4);
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false);
this.settingRepository = settingRepository;
}
@Test
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {
// Given
user = new User("Jerry", 12);
when(userRepository.insert(any(User.class))).then(new Answer<User>() {
int sequence = 1;
@Override
public User answer(InvocationOnMock invocation) throws Throwable {
User user = (User) invocation.getArgument(0);
user.setId(sequence++);
return user;
}
});
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
// When
User insertedUser = userService.register(user);
// Then
verify(userRepository).insert(user);
Assertions.assertNotNull(user.getId());
verify(mailClient).sendUserRegistrationMail(insertedUser);
}
@Test
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
// Given
user = new User("tom", 12);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_NAME_SHORT);
}
// Then
verify(userRepository, never()).insert(user);
}
@Test
void givenSmallAge_whenSaveUser_thenGiveYoungUserError() {
// Given
user = new User("jerry", 3);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_AGE_YOUNG);
}
// Then
verify(userRepository, never()).insert(user);
}
@Test
void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() {
// Given
user = new User("jerry", 12);
Mockito.reset(userRepository);
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE);
}
// Then
verify(userRepository, never()).insert(user);
}
}
package com.baeldung.junit5.mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.stubbing.Answer;
import com.baeldung.junit5.mockito.repository.MailClient;
import com.baeldung.junit5.mockito.repository.SettingRepository;
import com.baeldung.junit5.mockito.repository.UserRepository;
import com.baeldung.junit5.mockito.service.DefaultUserService;
import com.baeldung.junit5.mockito.service.Errors;
import com.baeldung.junit5.mockito.service.UserService;
@ExtendWith(MockitoExtension.class)
@RunWith(JUnitPlatform.class)
public class UserServiceUnitTest {
UserService userService;
SettingRepository settingRepository;
@Mock UserRepository userRepository;
@Mock MailClient mailClient;
User user;
@BeforeEach
void init(@Mock SettingRepository settingRepository) {
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
lenient().when(settingRepository.getUserMinAge()).thenReturn(10);
when(settingRepository.getUserNameMinLength()).thenReturn(4);
lenient().when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(false);
this.settingRepository = settingRepository;
}
@Test
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {
// Given
user = new User("Jerry", 12);
when(userRepository.insert(any(User.class))).then(new Answer<User>() {
int sequence = 1;
@Override
public User answer(InvocationOnMock invocation) throws Throwable {
User user = (User) invocation.getArgument(0);
user.setId(sequence++);
return user;
}
});
userService = new DefaultUserService(userRepository, settingRepository, mailClient);
// When
User insertedUser = userService.register(user);
// Then
verify(userRepository).insert(user);
Assertions.assertNotNull(user.getId());
verify(mailClient).sendUserRegistrationMail(insertedUser);
}
@Test
void givenShortName_whenSaveUser_thenGiveShortUsernameError() {
// Given
user = new User("tom", 12);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_NAME_SHORT);
}
// Then
verify(userRepository, never()).insert(user);
}
@Test
void givenSmallAge_whenSaveUser_thenGiveYoungUserError() {
// Given
user = new User("jerry", 3);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_AGE_YOUNG);
}
// Then
verify(userRepository, never()).insert(user);
}
@Test
void givenUserWithExistingName_whenSaveUser_thenGiveUsernameAlreadyExistsError() {
// Given
user = new User("jerry", 12);
Mockito.reset(userRepository);
when(userRepository.isUsernameAlreadyExists(any(String.class))).thenReturn(true);
// When
try {
userService.register(user);
fail("Should give an error");
} catch(Exception ex) {
assertEquals(ex.getMessage(), Errors.USER_NAME_DUPLICATE);
}
// Then
verify(userRepository, never()).insert(user);
}
}

View File

@@ -1,104 +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);
}
}
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);
}
}

View File

@@ -1,26 +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);
}
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);
}

View File

@@ -1,34 +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;
}
}
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;
}
}

View File

@@ -0,0 +1,26 @@
<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>
<artifactId>javafaker</artifactId>
<name>javafaker</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>mocks</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>${javafaker.version}</version>
</dependency>
</dependencies>
<properties>
<javafaker.version>0.15</javafaker.version>
</properties>
</project>

View File

@@ -0,0 +1,27 @@
<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>
<artifactId>jukito</artifactId>
<name>jukito</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>mocks</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.jukito</groupId>
<artifactId>jukito</artifactId>
<version>${jukito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jukito.version>1.5</jukito.version>
</properties>
</project>

View File

@@ -1,36 +1,36 @@
package com.baeldung.easymock;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class ArticleReader {
private List<BaeldungArticle> articles;
private Iterator<BaeldungArticle> articleIter;
public ArticleReader() {
this(new ArrayList<>());
}
public ArticleReader(List<BaeldungArticle> articles) {
this.articles = articles;
this.articleIter = this.articles.iterator();
}
public List<BaeldungArticle> ofTopic(String topic) {
return articles
.stream()
.filter(article -> article
.title()
.contains(topic))
.collect(toList());
}
public BaeldungArticle next() {
return this.articleIter.next();
}
package com.baeldung.easymock;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class ArticleReader {
private List<BaeldungArticle> articles;
private Iterator<BaeldungArticle> articleIter;
public ArticleReader() {
this(new ArrayList<>());
}
public ArticleReader(List<BaeldungArticle> articles) {
this.articles = articles;
this.articleIter = this.articles.iterator();
}
public List<BaeldungArticle> ofTopic(String topic) {
return articles
.stream()
.filter(article -> article
.title()
.contains(topic))
.collect(toList());
}
public BaeldungArticle next() {
return this.articleIter.next();
}
}

View File

@@ -1,25 +1,25 @@
package com.baeldung.easymock;
public class BaeldungArticle {
public static BaeldungArticle simpleArticle(String title, String content) {
return new BaeldungArticle(title, content);
}
private String title;
private String content;
private BaeldungArticle(String title, String content) {
this.title = title;
this.content = content;
}
public String title() {
return this.title;
}
public String content() {
return this.content;
}
package com.baeldung.easymock;
public class BaeldungArticle {
public static BaeldungArticle simpleArticle(String title, String content) {
return new BaeldungArticle(title, content);
}
private String title;
private String content;
private BaeldungArticle(String title, String content) {
this.title = title;
this.content = content;
}
public String title() {
return this.title;
}
public String content() {
return this.content;
}
}

View File

@@ -1,40 +1,40 @@
package com.baeldung.easymock;
import java.util.List;
public class BaeldungReader {
private ArticleReader articleReader;
private IArticleWriter articleWriter;
public BaeldungReader() {
}
;
public BaeldungReader(ArticleReader articleReader) {
this.articleReader = articleReader;
}
public BaeldungReader(IArticleWriter writer) {
this.articleWriter = writer;
}
public BaeldungReader(ArticleReader articleReader, IArticleWriter writer) {
this.articleReader = articleReader;
this.articleWriter = writer;
}
public BaeldungArticle readNext() {
return articleReader.next();
}
public List<BaeldungArticle> readTopic(String topic) {
return articleReader.ofTopic(topic);
}
public String write(String title, String content) {
return articleWriter.write(title, content);
}
package com.baeldung.easymock;
import java.util.List;
public class BaeldungReader {
private ArticleReader articleReader;
private IArticleWriter articleWriter;
public BaeldungReader() {
}
;
public BaeldungReader(ArticleReader articleReader) {
this.articleReader = articleReader;
}
public BaeldungReader(IArticleWriter writer) {
this.articleWriter = writer;
}
public BaeldungReader(ArticleReader articleReader, IArticleWriter writer) {
this.articleReader = articleReader;
this.articleWriter = writer;
}
public BaeldungArticle readNext() {
return articleReader.next();
}
public List<BaeldungArticle> readTopic(String topic) {
return articleReader.ofTopic(topic);
}
public String write(String title, String content) {
return articleWriter.write(title, content);
}
}

View File

@@ -1,7 +1,7 @@
package com.baeldung.easymock;
public interface IArticleWriter {
String write(String title, String content);
package com.baeldung.easymock;
public interface IArticleWriter {
String write(String title, String content);
}

View File

@@ -1,57 +1,57 @@
package com.baeldung.easymock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.*;
import org.junit.runner.RunWith;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
@RunWith(EasyMockRunner.class)
public class BaeldungReaderAnnotatedUnitTest {
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
verify(mockArticleReader);
}
@Mock BaeldungReader mockBaeldungReader;
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
baeldungReader.write("title", "content");
verify(mockArticleWriter);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
}
package com.baeldung.easymock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.*;
import org.junit.runner.RunWith;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
@RunWith(EasyMockRunner.class)
public class BaeldungReaderAnnotatedUnitTest {
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
verify(mockArticleReader);
}
@Mock BaeldungReader mockBaeldungReader;
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
baeldungReader.write("title", "content");
verify(mockArticleWriter);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
}

View File

@@ -1,57 +1,57 @@
package com.baeldung.easymock;
import org.easymock.EasyMockRule;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.*;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
public class BaeldungReaderAnnotatedWithRuleUnitTest {
@Rule public EasyMockRule mockRule = new EasyMockRule(this);
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
verify(mockArticleReader);
}
@Mock BaeldungReader mockBaeldungReader;
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
baeldungReader.write("title", "content");
verify(mockArticleWriter);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
}
package com.baeldung.easymock;
import org.easymock.EasyMockRule;
import org.easymock.Mock;
import org.easymock.TestSubject;
import org.junit.*;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
public class BaeldungReaderAnnotatedWithRuleUnitTest {
@Rule public EasyMockRule mockRule = new EasyMockRule(this);
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
verify(mockArticleReader);
}
@Mock BaeldungReader mockBaeldungReader;
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
baeldungReader.write("title", "content");
verify(mockArticleWriter);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
}

View File

@@ -1,27 +1,27 @@
package com.baeldung.easymock;
import org.easymock.*;
import org.junit.*;
import static org.easymock.EasyMock.*;
public class BaeldungReaderMockDelegationUnitTest {
EasyMockSupport easyMockSupport = new EasyMockSupport();
@Test
public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() {
ArticleReader mockArticleReader = easyMockSupport.createMock(ArticleReader.class);
IArticleWriter mockArticleWriter = easyMockSupport.createMock(IArticleWriter.class);
BaeldungReader baeldungReader = new BaeldungReader(mockArticleReader, mockArticleWriter);
expect(mockArticleReader.next()).andReturn(null);
expect(mockArticleWriter.write("title", "content")).andReturn("");
easyMockSupport.replayAll();
baeldungReader.readNext();
baeldungReader.write("title", "content");
easyMockSupport.verifyAll();
}
package com.baeldung.easymock;
import org.easymock.*;
import org.junit.*;
import static org.easymock.EasyMock.*;
public class BaeldungReaderMockDelegationUnitTest {
EasyMockSupport easyMockSupport = new EasyMockSupport();
@Test
public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() {
ArticleReader mockArticleReader = easyMockSupport.createMock(ArticleReader.class);
IArticleWriter mockArticleWriter = easyMockSupport.createMock(IArticleWriter.class);
BaeldungReader baeldungReader = new BaeldungReader(mockArticleReader, mockArticleWriter);
expect(mockArticleReader.next()).andReturn(null);
expect(mockArticleWriter.write("title", "content")).andReturn("");
easyMockSupport.replayAll();
baeldungReader.readNext();
baeldungReader.write("title", "content");
easyMockSupport.verifyAll();
}
}

View File

@@ -1,42 +1,42 @@
package com.baeldung.easymock;
import org.easymock.*;
import org.junit.*;
import org.junit.runner.RunWith;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
@RunWith(EasyMockRunner.class)
public class BaeldungReaderMockSupportUnitTest extends EasyMockSupport {
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@Test
public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
expect(mockArticleWriter.write("title", "content")).andReturn("BAEL-201801");
replayAll();
Exception expectedException = null;
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception exception) {
expectedException = exception;
}
String articleId = baeldungReader.write("title", "content");
verifyAll();
assertEquals(NoSuchElementException.class, expectedException.getClass());
assertEquals("BAEL-201801", articleId);
}
package com.baeldung.easymock;
import org.easymock.*;
import org.junit.*;
import org.junit.runner.RunWith;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
@RunWith(EasyMockRunner.class)
public class BaeldungReaderMockSupportUnitTest extends EasyMockSupport {
@TestSubject BaeldungReader baeldungReader = new BaeldungReader();
@Mock ArticleReader mockArticleReader;
@Mock IArticleWriter mockArticleWriter;
@Test
public void givenBaeldungReader_whenReadAndWriteSequencially_thenWorks() {
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
expect(mockArticleWriter.write("title", "content")).andReturn("BAEL-201801");
replayAll();
Exception expectedException = null;
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception exception) {
expectedException = exception;
}
String articleId = baeldungReader.write("title", "content");
verifyAll();
assertEquals(NoSuchElementException.class, expectedException.getClass());
assertEquals("BAEL-201801", articleId);
}
}

View File

@@ -1,105 +1,105 @@
package com.baeldung.easymock;
import org.junit.*;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
public class BaeldungReaderUnitTest {
private BaeldungReader baeldungReader;
private ArticleReader mockArticleReader;
private IArticleWriter mockArticleWriter;
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
mockArticleReader = mock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
BaeldungArticle article = baeldungReader.readNext();
verify(mockArticleReader);
assertEquals(null, article);
}
@Test
public void givenBaeldungReader_whenReadNextAndSkimTopics_thenAllAllowed() {
mockArticleReader = strictMock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next()).andReturn(null);
expect(mockArticleReader.ofTopic("easymock")).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
baeldungReader.readTopic("easymock");
verify(mockArticleReader);
}
@Test
public void givenBaeldungReader_whenReadNextAndOthers_thenAllowed() {
mockArticleReader = niceMock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
baeldungReader.readTopic("easymock");
verify(mockArticleReader);
}
@Test
public void givenBaeldungReader_whenWriteMaliciousContent_thenArgumentIllegal() {
mockArticleWriter = mock(IArticleWriter.class);
baeldungReader = new BaeldungReader(mockArticleWriter);
expect(mockArticleWriter.write("easymock", "<body onload=alert('baeldung')>")).andThrow(new IllegalArgumentException());
replay(mockArticleWriter);
Exception expectedException = null;
try {
baeldungReader.write("easymock", "<body onload=alert('baeldung')>");
} catch (Exception exception) {
expectedException = exception;
}
verify(mockArticleWriter);
assertEquals(IllegalArgumentException.class, expectedException.getClass());
}
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
mockArticleWriter = mock(IArticleWriter.class);
baeldungReader = new BaeldungReader(mockArticleWriter);
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
String articleId = baeldungReader.write("title", "content");
verify(mockArticleWriter);
assertEquals(null, articleId);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
ArticleReader mockArticleReader = mock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
package com.baeldung.easymock;
import org.junit.*;
import java.util.NoSuchElementException;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.assertEquals;
public class BaeldungReaderUnitTest {
private BaeldungReader baeldungReader;
private ArticleReader mockArticleReader;
private IArticleWriter mockArticleWriter;
@Test
public void givenBaeldungReader_whenReadNext_thenNextArticleRead() {
mockArticleReader = mock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
BaeldungArticle article = baeldungReader.readNext();
verify(mockArticleReader);
assertEquals(null, article);
}
@Test
public void givenBaeldungReader_whenReadNextAndSkimTopics_thenAllAllowed() {
mockArticleReader = strictMock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next()).andReturn(null);
expect(mockArticleReader.ofTopic("easymock")).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
baeldungReader.readTopic("easymock");
verify(mockArticleReader);
}
@Test
public void givenBaeldungReader_whenReadNextAndOthers_thenAllowed() {
mockArticleReader = niceMock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next()).andReturn(null);
replay(mockArticleReader);
baeldungReader.readNext();
baeldungReader.readTopic("easymock");
verify(mockArticleReader);
}
@Test
public void givenBaeldungReader_whenWriteMaliciousContent_thenArgumentIllegal() {
mockArticleWriter = mock(IArticleWriter.class);
baeldungReader = new BaeldungReader(mockArticleWriter);
expect(mockArticleWriter.write("easymock", "<body onload=alert('baeldung')>")).andThrow(new IllegalArgumentException());
replay(mockArticleWriter);
Exception expectedException = null;
try {
baeldungReader.write("easymock", "<body onload=alert('baeldung')>");
} catch (Exception exception) {
expectedException = exception;
}
verify(mockArticleWriter);
assertEquals(IllegalArgumentException.class, expectedException.getClass());
}
@Test
public void givenBaeldungReader_whenWrite_thenWriterCalled() {
mockArticleWriter = mock(IArticleWriter.class);
baeldungReader = new BaeldungReader(mockArticleWriter);
expect(mockArticleWriter.write("title", "content")).andReturn(null);
replay(mockArticleWriter);
String articleId = baeldungReader.write("title", "content");
verify(mockArticleWriter);
assertEquals(null, articleId);
}
@Test
public void givenArticlesInReader_whenReadTillEnd_thenThrowException() {
ArticleReader mockArticleReader = mock(ArticleReader.class);
baeldungReader = new BaeldungReader(mockArticleReader);
expect(mockArticleReader.next())
.andReturn(null)
.times(2)
.andThrow(new NoSuchElementException());
replay(mockArticleReader);
try {
for (int i = 0; i < 3; i++) {
baeldungReader.readNext();
}
} catch (Exception ignored) {
}
verify(mockArticleReader);
}
}

View File

@@ -2,8 +2,8 @@
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>
<artifactId>testing-modules</artifactId>
<name>testing-modules</name>
<artifactId>testing-libraries</artifactId>
<name>testing-libraries</name>
<packaging>pom</packaging>
<parent>
@@ -31,7 +31,6 @@
<module>selenium-junit-testng</module>
<module>spring-testing</module>
<module>test-containers</module>
<module>testing</module>
<module>testng</module>
<module>junit-5-basics</module>
<module>easymock</module>

View File

@@ -1,49 +1,49 @@
package com.baeldung.restassured;
public class Odd {
float price;
int status;
float ck;
String name;
Odd(float price, int status, float ck, String name) {
this.price = price;
this.status = status;
this.ck = ck;
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public float getCk() {
return ck;
}
public void setCk(float ck) {
this.ck = ck;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.baeldung.restassured;
public class Odd {
float price;
int status;
float ck;
String name;
Odd(float price, int status, float ck, String name) {
this.price = price;
this.status = status;
this.ck = ck;
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public float getCk() {
return ck;
}
public void setCk(float ck) {
this.ck = ck;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

0
testing-modules/selenium-junit-testng/geckodriver.mac Executable file → Normal file
View File

View File

@@ -1,23 +1,23 @@
package org.baeldung.reflectiontestutils.repository;
public class Employee {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String employeeToString() {
return "id: " + getId() + "; name: " + getName();
}
}
package org.baeldung.reflectiontestutils.repository;
public class Employee {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String employeeToString() {
return "id: " + getId() + "; name: " + getName();
}
}

View File

@@ -1,14 +1,14 @@
package org.baeldung.reflectiontestutils.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class EmployeeService {
@Autowired
private HRService hrService;
public String findEmployeeStatus(Integer employeeId) {
return "Employee " + employeeId + " status: " + hrService.getEmployeeStatus(employeeId);
}
}
package org.baeldung.reflectiontestutils.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class EmployeeService {
@Autowired
private HRService hrService;
public String findEmployeeStatus(Integer employeeId) {
return "Employee " + employeeId + " status: " + hrService.getEmployeeStatus(employeeId);
}
}

View File

@@ -1,11 +1,11 @@
package org.baeldung.reflectiontestutils.repository;
import org.springframework.stereotype.Component;
@Component
public class HRService {
public String getEmployeeStatus(Integer employeeId) {
return "Inactive";
}
}
package org.baeldung.reflectiontestutils.repository;
import org.springframework.stereotype.Component;
@Component
public class HRService {
public String getEmployeeStatus(Integer employeeId) {
return "Inactive";
}
}

View File

@@ -1,46 +1,46 @@
package org.baeldung.reflectiontestutils;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import org.baeldung.reflectiontestutils.repository.Employee;
import org.baeldung.reflectiontestutils.repository.EmployeeService;
import org.baeldung.reflectiontestutils.repository.HRService;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
import static org.mockito.Mockito.when;
public class ReflectionTestUtilsUnitTest {
@Test
public void whenNonPublicField_thenReflectionTestUtilsSetField() {
Employee employee = new Employee();
ReflectionTestUtils.setField(employee, "id", 1);
assertTrue(employee.getId().equals(1));
}
@Test
public void whenNonPublicMethod_thenReflectionTestUtilsInvokeMethod() {
Employee employee = new Employee();
ReflectionTestUtils.setField(employee, "id", 1);
employee.setName("Smith, John");
assertTrue(ReflectionTestUtils.invokeMethod(employee, "employeeToString").equals("id: 1; name: Smith, John"));
}
@Test
public void whenInjectingMockOfDependency_thenReflectionTestUtilsSetField() {
Employee employee = new Employee();
ReflectionTestUtils.setField(employee, "id", 1);
employee.setName("Smith, John");
HRService hrService = mock(HRService.class);
when(hrService.getEmployeeStatus(employee.getId())).thenReturn("Active");
EmployeeService employeeService = new EmployeeService();
// Inject mock into the private field
ReflectionTestUtils.setField(employeeService, "hrService", hrService);
assertEquals("Employee " + employee.getId() + " status: Active", employeeService.findEmployeeStatus(employee.getId()));
}
}
package org.baeldung.reflectiontestutils;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import org.baeldung.reflectiontestutils.repository.Employee;
import org.baeldung.reflectiontestutils.repository.EmployeeService;
import org.baeldung.reflectiontestutils.repository.HRService;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
import static org.mockito.Mockito.when;
public class ReflectionTestUtilsUnitTest {
@Test
public void whenNonPublicField_thenReflectionTestUtilsSetField() {
Employee employee = new Employee();
ReflectionTestUtils.setField(employee, "id", 1);
assertTrue(employee.getId().equals(1));
}
@Test
public void whenNonPublicMethod_thenReflectionTestUtilsInvokeMethod() {
Employee employee = new Employee();
ReflectionTestUtils.setField(employee, "id", 1);
employee.setName("Smith, John");
assertTrue(ReflectionTestUtils.invokeMethod(employee, "employeeToString").equals("id: 1; name: Smith, John"));
}
@Test
public void whenInjectingMockOfDependency_thenReflectionTestUtilsSetField() {
Employee employee = new Employee();
ReflectionTestUtils.setField(employee, "id", 1);
employee.setName("Smith, John");
HRService hrService = mock(HRService.class);
when(hrService.getEmployeeStatus(employee.getId())).thenReturn("Active");
EmployeeService employeeService = new EmployeeService();
// Inject mock into the private field
ReflectionTestUtils.setField(employeeService, "hrService", hrService);
assertEquals("Employee " + employee.getId() + " status: Active", employeeService.findEmployeeStatus(employee.getId()));
}
}

View File

@@ -1,24 +0,0 @@
=========
## Mutation Testing
### Relevant Articles:
- [Mutation Testing with PITest](http://www.baeldung.com/java-mutation-testing-with-pitest)
- [Intro to JaCoCo](http://www.baeldung.com/jacoco)
- [AssertJs Java 8 Features](http://www.baeldung.com/assertJ-java-8-features)
- [AssertJ for Guava](http://www.baeldung.com/assertJ-for-guava)
- [Introduction to AssertJ](http://www.baeldung.com/introduction-to-assertj)
- [Cucumber and Scenario Outline](http://www.baeldung.com/cucumber-scenario-outline)
- [Testing with Google Truth](http://www.baeldung.com/google-truth)
- [Testing with JGoTesting](http://www.baeldung.com/jgotesting)
- [Introduction to JUnitParams](http://www.baeldung.com/junit-params)
- [Cucumber Java 8 Support](http://www.baeldung.com/cucumber-java-8-support)
- [Introduction to Lambda Behave](http://www.baeldung.com/lambda-behave)
- [Introduction to Jukito](http://www.baeldung.com/jukito)
- [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners)
- [Guide to JSpec](http://www.baeldung.com/jspec)
- [Custom Assertions with AssertJ](http://www.baeldung.com/assertj-custom-assertion)
- [Using Conditions with AssertJ Assertions](http://www.baeldung.com/assertj-conditions)
- [A Guide to JavaFaker](https://www.baeldung.com/java-faker)
- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java)
- [AssertJ Exception Assertions](http://www.baeldung.com/assertj-exception-assertion)

View File

@@ -1,183 +0,0 @@
<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>com.baeldung</groupId>
<artifactId>testing</artifactId>
<version>0.1-SNAPSHOT</version>
<name>testing</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.insightfullogic</groupId>
<artifactId>lambda-behave</artifactId>
<version>${lambda-behave.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-guava</artifactId>
<version>${assertj-guava.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java8</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.pitest</groupId>
<artifactId>pitest-parent</artifactId>
<version>${pitest.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>${truth.version}</version>
</dependency>
<dependency>
<groupId>com.google.truth.extensions</groupId>
<artifactId>truth-java8-extension</artifactId>
<version>${truth.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>${jUnitParams.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jgotesting</groupId>
<artifactId>jgotesting</artifactId>
<version>${jgotesting.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jukito</groupId>
<artifactId>jukito</artifactId>
<version>${jukito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.javalite</groupId>
<artifactId>javalite-common</artifactId>
<version>${javalite.version}</version>
</dependency>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>${javafaker.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<version>${pitest.version}</version>
<configuration>
<targetClasses>
<param>com.baeldung.testing.mutation.*</param>
</targetClasses>
<targetTests>
<param>com.baeldung.mutation.test.*</param>
</targetTests>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
<execution>
<id>jacoco-check</id>
<goals>
<goal>check</goal>
</goals>
<configuration>
<rules>
<rule>
<element>PACKAGE</element>
<limits>
<limit>
<counter>LINE</counter>
<value>COVEREDRATIO</value>
<minimum>0</minimum>
</limit>
</limits>
</rule>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.assertj</groupId>
<artifactId>assertj-assertions-generator-maven-plugin</artifactId>
<version>${assertj-generator.version}</version>
<configuration>
<classes>
<param>com.baeldung.testing.assertj.custom.Person</param>
</classes>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<cucumber.version>1.2.5</cucumber.version>
<pitest.version>1.1.10</pitest.version>
<jacoco.version>0.7.7.201606060606</jacoco.version>
<guava.version>21.0</guava.version>
<assertj-guava.version>3.1.0</assertj-guava.version>
<assertj-core.version>3.9.0</assertj-core.version>
<assertj-generator.version>2.1.0</assertj-generator.version>
<truth.version>0.32</truth.version>
<jUnitParams.version>1.1.0</jUnitParams.version>
<jgotesting.version>0.12</jgotesting.version>
<javalite.version>1.4.13</javalite.version>
<lambda-behave.version>0.4</lambda-behave.version>
<assertj-guava.version>3.0.0</assertj-guava.version>
<jukito.version>1.5</jukito.version>
<javafaker.version>0.15</javafaker.version>
</properties>
</project>

View File

@@ -1,7 +0,0 @@
package com.baeldung.cucumber;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}

View File

@@ -1,41 +0,0 @@
package com.baeldung.jspec;
public abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Animal other = (Animal) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}

View File

@@ -1,48 +0,0 @@
package com.baeldung.jspec;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Cage {
private Set<Animal> animals = new HashSet<>();
public void put(Animal animal) {
animals.add(animal);
}
public void put(Animal... animals) {
this.animals.addAll(Arrays.asList(animals));
}
public Animal release(Animal animal) {
return animals.remove(animal) ? animal : null;
}
public void open() {
animals.clear();
}
public boolean hasAnimals() {
return animals.size() > 0;
}
public boolean isEmpty() {
return animals.isEmpty();
}
public Set<Animal> getAnimals() {
return this.animals;
}
public int size() {
return animals.size();
}
@Override
public String toString() {
return "Cage [animals=" + animals + "]";
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.jspec;
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public String toString() {
return "Cat [name=" + name + "]";
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.jspec;
public class Dog extends Animal {
public Dog(String name) {
super(name);
}
@Override
public String toString() {
return "Dog [name=" + name + "]";
}
}

View File

@@ -1,11 +0,0 @@
package com.baeldung.junit;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
}

View File

@@ -1,24 +0,0 @@
package com.baeldung.lambdabehave;
public class Calculator {
private int x;
private int y;
Calculator(int x, int y) {
this.x = x;
this.y = y;
}
public int add() {
return this.x + this.y;
}
public int divide(int a, int b) {
return a / b;
}
public int add(int a, int b) {
return a + b;
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.testing.assertj;
public class Dog {
private String name;
private Float weight;
public Dog(String name, Float weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return name;
}
public Float getWeight() {
return weight;
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.testing.assertj;
public class Member {
private String name;
private int age;
public Member(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}

View File

@@ -1,19 +0,0 @@
package com.baeldung.testing.assertj;
public class Person {
private String name;
private Integer age;
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
}

View File

@@ -1,32 +0,0 @@
package com.baeldung.testing.assertj.custom;
import java.util.ArrayList;
import java.util.List;
public class Person {
private String fullName;
private int age;
private List<String> nicknames;
public Person(String fullName, int age) {
this.fullName = fullName;
this.age = age;
this.nicknames = new ArrayList<>();
}
public void addNickname(String nickname) {
nicknames.add(nickname);
}
public String getFullName() {
return fullName;
}
public int getAge() {
return age;
}
public List<String> getNicknames() {
return nicknames;
}
}

View File

@@ -1,15 +0,0 @@
package com.baeldung.testing.mutation;
public class Palindrome {
public boolean isPalindrome(String inputString) {
if (inputString.length() == 0) {
return true;
} else {
char firstChar = inputString.charAt(0);
char lastChar = inputString.charAt(inputString.length() - 1);
String mid = inputString.substring(1, inputString.length() - 1);
return (firstChar == lastChar) && isPalindrome(mid);
}
}
}

View File

@@ -1,57 +0,0 @@
package com.baeldung.testing.truth;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
public class User implements Comparable<User> {
private String name = "John Doe";
private List<String> emails = Arrays.asList("contact@baeldung.com", "staff@baeldung.com");
public User() {
}
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
@Override
public int hashCode() {
int hash = 5;
hash = 37 * hash + Objects.hashCode(this.name);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final User other = (User) obj;
return Objects.equals(this.name, other.name);
}
@Override
public int compareTo(User o) {
return this.getName()
.compareToIgnoreCase(o.getName());
}
}

View File

@@ -1,46 +0,0 @@
package com.baeldung.testing.truth;
import com.google.common.truth.ComparableSubject;
import com.google.common.truth.FailureStrategy;
import com.google.common.truth.IterableSubject;
import com.google.common.truth.SubjectFactory;
import com.google.common.truth.Truth;
public class UserSubject extends ComparableSubject<UserSubject, User> {
private UserSubject(FailureStrategy failureStrategy, User target) {
super(failureStrategy, target);
}
private static final SubjectFactory<UserSubject, User> USER_SUBJECT_FACTORY = new SubjectFactory<UserSubject, User>() {
@Override
public UserSubject getSubject(FailureStrategy failureStrategy, User target) {
return new UserSubject(failureStrategy, target);
}
};
public static UserSubject assertThat(User user) {
return Truth.assertAbout(USER_SUBJECT_FACTORY)
.that(user);
}
// Our API begins here
public void hasName(String name) {
if (!actual().getName()
.equals(name)) {
fail("has name", name);
}
}
public void hasNameIgnoringCase(String name) {
if (!actual().getName()
.equalsIgnoreCase(name)) {
fail("has name ignoring case", name);
}
}
public IterableSubject emails() {
return Truth.assertThat(actual().getEmails());
}
}

View File

@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -1,126 +0,0 @@
package com.baeldung.jspec;
import static org.javalite.test.jspec.JSpec.$;
import static org.javalite.test.jspec.JSpec.expect;
import static org.javalite.test.jspec.JSpec.the;
import java.util.Set;
import org.javalite.test.jspec.DifferenceExpectation;
import org.junit.Test;
public class CageUnitTest {
Cat tomCat = new Cat("Tom");
Cat felixCat = new Cat("Felix");
Dog boltDog = new Dog("Bolt");
Cage cage = new Cage();
@Test
public void puttingAnimals_shouldIncreaseCageSize() {
// When
cage.put(tomCat, boltDog);
// Then
the(cage.size()).shouldEqual(2);
}
@Test
public void releasingAnimals_shouldDecreaseCageSize() {
// When
cage.put(tomCat, boltDog);
cage.release(tomCat);
// Then
the(cage.size()).shouldEqual(1);
}
@Test
public void puttingAnimals_shouldLeaveThemInsideTheCage() {
// When
cage.put(tomCat, boltDog);
// Then
the(cage).shouldHave("animals");
}
@Test
public void openingTheCage_shouldReleaseAllAnimals() {
// When
cage.put(tomCat, boltDog);
// Then
the(cage).shouldNotBe("empty");
// When
cage.open();
// Then
the(cage).shouldBe("empty");
the(cage.isEmpty()).shouldBeTrue();
}
@Test
public void comparingTwoDogs() {
// When
Dog firstDog = new Dog("Rex");
Dog secondDog = new Dog("Rex");
// Then
$(firstDog).shouldEqual(secondDog);
$(firstDog).shouldNotBeTheSameAs(secondDog);
}
@Test
public void puttingCatsOnly_shouldLetCageAnimalsToContainCats() {
// When
cage.put(tomCat, felixCat);
// Then
Set<Animal> animals = cage.getAnimals();
the(animals).shouldContain(tomCat);
the(animals).shouldContain(felixCat);
the(animals).shouldNotContain(boltDog);
}
@Test
public void puttingCatsOnly_shouldLetCageToContainCats() {
// When
cage.put(tomCat, felixCat);
// Then
// Check with toString of the tested objects
the(cage).shouldContain(tomCat);
the(cage).shouldContain(felixCat);
the(cage).shouldNotContain(boltDog);
}
@Test
public void puttingMoreAnimals_shouldChangeSize() {
// When
cage.put(tomCat, boltDog);
// Then
expect( new DifferenceExpectation<Integer>(cage.size()) {
@Override
public Integer exec() {
cage.release(tomCat);
return cage.size();
}
} );
}
@Test
public void releasingTheDog_shouldReleaseAnAnimalOfDogType() {
// When
cage.put(boltDog);
Animal releasedAnimal = cage.release(boltDog);
// Then
the(releasedAnimal).shouldNotBeNull();
the(releasedAnimal).shouldBeA(Dog.class);
}
}

View File

@@ -1,57 +0,0 @@
package com.baeldung.jspec;
import static org.javalite.test.jspec.JSpec.$;
import static org.javalite.test.jspec.JSpec.a;
import static org.javalite.test.jspec.JSpec.expect;
import static org.javalite.test.jspec.JSpec.it;
import static org.javalite.test.jspec.JSpec.the;
import java.util.Arrays;
import java.util.List;
import org.javalite.test.jspec.ExceptionExpectation;
import org.junit.Test;
public class JSpecUnitTest {
@Test
public void onePlusTwo_shouldEqualThree() {
$(1 + 2).shouldEqual(3);
a(1 + 2).shouldEqual(3);
the(1 + 2).shouldEqual(3);
it(1 + 2).shouldEqual(3);
}
@Test
public void messageShouldContainJSpec() {
String message = "Welcome to JSpec demo";
// The message should not be empty
the(message).shouldNotBe("empty");
// The message should contain JSpec
the(message).shouldContain("JSpec");
}
public void colorsListShouldContainRed() {
List<String> colorsList = Arrays.asList("red", "green", "blue");
$(colorsList).shouldContain("red");
}
public void guessedNumberShouldEqualHiddenNumber() {
Integer guessedNumber = 11;
Integer hiddenNumber = 11;
$(guessedNumber).shouldEqual(hiddenNumber);
$(guessedNumber).shouldNotBeTheSameAs(hiddenNumber);
}
@Test
public void dividingByThero_shouldThrowArithmeticException() {
expect(new ExceptionExpectation<ArithmeticException>(ArithmeticException.class) {
@Override
public void exec() throws ArithmeticException {
System.out.println(1 / 0);
}
} );
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.junit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AdditionUnitTest {
Calculator calculator = new Calculator();
@Test
public void testAddition() {
assertEquals("addition", 8, calculator.add(5, 3));
}
}

View File

@@ -1,101 +0,0 @@
package com.baeldung.junit;
import org.junit.Test;
import java.util.Arrays;
import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.*;
/**
* Unit test that demonstrate the different assertions available within JUnit 4
*/
public class AssertionsUnitTest {
@Test
public void whenAssertingEquality_thenEqual() {
String expected = "Baeldung";
String actual = "Baeldung";
assertEquals(expected, actual);
}
@Test
public void whenAssertingEqualityWithMessage_thenEqual() {
String expected = "Baeldung";
String actual = "Baeldung";
assertEquals("failure - strings are not equal", expected, actual);
}
@Test
public void whenAssertingArraysEquality_thenEqual() {
char[] expected = { 'J', 'u', 'n', 'i', 't' };
char[] actual = "Junit".toCharArray();
assertArrayEquals(expected, actual);
}
@Test
public void givenNullArrays_whenAssertingArraysEquality_thenEqual() {
int[] expected = null;
int[] actual = null;
assertArrayEquals(expected, actual);
}
@Test
public void whenAssertingNull_thenTrue() {
Object car = null;
assertNull("The car should be null", car);
}
@Test
public void whenAssertingNotNull_thenTrue() {
Object car = new Object();
assertNotNull("The car should not be null", car);
}
@Test
public void whenAssertingNotSameObject_thenDifferent() {
Object cat = new Object();
Object dog = new Object();
assertNotSame(cat, dog);
}
@Test
public void whenAssertingSameObject_thenSame() {
Object cat = new Object();
assertSame(cat, cat);
}
@Test
public void whenAssertingConditions_thenVerified() {
assertTrue("5 is greater then 4", 5 > 4);
assertFalse("5 is not greater then 6", 5 > 6);
}
@Test
public void when_thenNotFailed() {
try {
methodThatShouldThrowException();
fail("Exception not thrown");
} catch (UnsupportedOperationException e) {
assertEquals("Operation Not Supported", e.getMessage());
}
}
private void methodThatShouldThrowException() {
throw new UnsupportedOperationException("Operation Not Supported");
}
@Test
public void testAssertThatHasItems() {
assertThat(Arrays.asList("Java", "Kotlin", "Scala"), hasItems("Java", "Kotlin"));
}
}

View File

@@ -1,18 +0,0 @@
package com.baeldung.junit;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
public class BlockingTestRunner extends BlockJUnit4ClassRunner {
public BlockingTestRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
System.out.println("invoking: " + method.getName());
return super.methodInvoker(method, test);
}
}

View File

@@ -1,17 +0,0 @@
package com.baeldung.junit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.junit.Assert.assertEquals;
@RunWith(JUnit4.class)
public class CalculatorUnitTest {
Calculator calculator = new Calculator();
@Test
public void testAddition() {
assertEquals("addition", 8, calculator.add(5, 3));
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.junit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SubstractionUnitTest {
Calculator calculator = new Calculator();
@Test
public void substraction() {
assertEquals("substraction", 2, calculator.sub(5, 3));
}
}

View File

@@ -1,12 +0,0 @@
package com.baeldung.junit;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
AdditionUnitTest.class,
SubstractionUnitTest.class})
public class SuiteUnitTest {
}

View File

@@ -1,41 +0,0 @@
package com.baeldung.junit;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import java.lang.reflect.Method;
public class TestRunner extends Runner {
private Class testClass;
public TestRunner(Class testClass) {
super();
this.testClass = testClass;
}
@Override
public Description getDescription() {
return Description.createTestDescription(testClass, "My runner description");
}
@Override
public void run(RunNotifier notifier) {
System.out.println("running the tests from MyRunner: " + testClass);
try {
Object testObject = testClass.newInstance();
for (Method method : testClass.getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
notifier.fireTestStarted(Description
.createTestDescription(testClass, method.getName()));
method.invoke(testObject);
notifier.fireTestFinished(Description
.createTestDescription(testClass, method.getName()));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -1,54 +0,0 @@
package com.baeldung.lambdabehave;
import com.insightfullogic.lambdabehave.JunitSuiteRunner;
import com.insightfullogic.lambdabehave.Suite;
import com.insightfullogic.lambdabehave.generators.Generator;
import com.insightfullogic.lambdabehave.generators.SourceGenerator;
import org.junit.runner.RunWith;
@RunWith(JunitSuiteRunner.class)
public class CalculatorUnitTest {
private Calculator calculator;
{
Suite.describe("Lambda behave example tests", it -> {
it.isSetupWith(() -> {
calculator = new Calculator(1, 2);
});
it.should("Add the given numbers", expect -> {
expect.that(calculator.add()).is(3);
});
it.should("Throw an exception if divide by 0", expect -> {
expect.exception(ArithmeticException.class, () -> {
calculator.divide(1, 0);
});
});
it.uses(2, 3, 5)
.and(23, 10, 33)
.toShow("%d + %d = %d", (expect, a, b, c) -> {
expect.that(calculator.add(a, b)).is(c);
});
it.requires(2)
.example(Generator.asciiStrings())
.toShow("Reversing a String twice returns the original String", (expect, str) -> {
String same = new StringBuilder(str).reverse()
.reverse()
.toString();
expect.that(same)
.isEqualTo(str);
});
it.requires(2)
.withSource(SourceGenerator.deterministicNumbers(5626689007407L))
.example(Generator.asciiStrings())
.toShow("Reversing a String twice returns the original String", (expect, str) -> {
String same = new StringBuilder(str).reverse()
.reverse()
.toString();
expect.that(same)
.isEqualTo(str);
});
});
}
}

View File

@@ -1,34 +0,0 @@
package com.baeldung.mutation.test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.testing.mutation.Palindrome;
public class PalindromeUnitTest {
@Test
public void whenEmptyString_thanAccept() {
Palindrome palindromeTester = new Palindrome();
assertTrue(palindromeTester.isPalindrome("noon"));
}
@Test
public void whenPalindrom_thanAccept() {
Palindrome palindromeTester = new Palindrome();
assertTrue(palindromeTester.isPalindrome("noon"));
}
@Test
public void whenNotPalindrom_thanReject(){
Palindrome palindromeTester = new Palindrome();
assertFalse(palindromeTester.isPalindrome("box"));
}
@Test
public void whenNearPalindrom_thanReject(){
Palindrome palindromeTester = new Palindrome();
assertFalse(palindromeTester.isPalindrome("neon"));
}
}

View File

@@ -1,72 +0,0 @@
package com.baeldung.testing.assertj;
import static org.assertj.core.api.Assertions.allOf;
import static org.assertj.core.api.Assertions.anyOf;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.not;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.api.Condition;
import org.junit.Test;
public class AssertJConditionUnitTest {
private Condition<Member> senior = new Condition<>(m -> m.getAge() >= 60, "senior");
private Condition<Member> nameJohn = new Condition<>(m -> m.getName().equalsIgnoreCase("John"), "name John");
@Test
public void whenUsingMemberAgeCondition_thenCorrect() {
Member member = new Member("John", 65);
assertThat(member).is(senior);
try {
assertThat(member).isNot(senior);
fail();
} catch (AssertionError e) {
assertThat(e).hasMessageContaining("not to be <senior>");
}
}
@Test
public void whenUsingMemberNameCondition_thenCorrect() {
Member member = new Member("Jane", 60);
assertThat(member).doesNotHave(nameJohn);
try {
assertThat(member).has(nameJohn);
fail();
} catch (AssertionError e) {
assertThat(e).hasMessageContaining("<name John>");
}
}
@Test
public void whenCollectionConditionsAreSatisfied_thenCorrect() {
List<Member> members = new ArrayList<>();
members.add(new Member("Alice", 50));
members.add(new Member("Bob", 60));
assertThat(members).haveExactly(1, senior);
assertThat(members).doNotHave(nameJohn);
}
@Test
public void whenCombiningAllOfConditions_thenCorrect() {
Member john = new Member("John", 60);
Member jane = new Member("Jane", 50);
assertThat(john).is(allOf(senior, nameJohn));
assertThat(jane).is(allOf(not(nameJohn), not(senior)));
}
@Test
public void whenCombiningAnyOfConditions_thenCorrect() {
Member john = new Member("John", 50);
Member jane = new Member("Jane", 60);
assertThat(john).is(anyOf(senior, nameJohn));
assertThat(jane).is(anyOf(nameJohn, senior));
}
}

View File

@@ -1,117 +0,0 @@
package com.baeldung.testing.assertj;
import org.assertj.core.util.Maps;
import org.junit.Ignore;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import static org.assertj.core.api.Assertions.*;
public class AssertJCoreUnitTest {
@Test
public void whenComparingReferences_thenNotEqual() throws Exception {
Dog fido = new Dog("Fido", 5.15f);
Dog fidosClone = new Dog("Fido", 5.15f);
assertThat(fido).isNotEqualTo(fidosClone);
}
@Test
public void whenComparingFields_thenEqual() throws Exception {
Dog fido = new Dog("Fido", 5.15f);
Dog fidosClone = new Dog("Fido", 5.15f);
assertThat(fido).isEqualToComparingFieldByFieldRecursively(fidosClone);
}
@Test
public void whenCheckingForElement_thenContains() throws Exception {
List<String> list = Arrays.asList("1", "2", "3");
assertThat(list).contains("1");
}
@Test
public void whenCheckingForElement_thenMultipleAssertions() throws Exception {
List<String> list = Arrays.asList("1", "2", "3");
assertThat(list).isNotEmpty();
assertThat(list).startsWith("1");
assertThat(list).doesNotContainNull();
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
}
@Test
public void whenCheckingRunnable_thenIsInterface() throws Exception {
assertThat(Runnable.class).isInterface();
}
@Test
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
char someCharacter = 'c';
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
}
@Test
public void whenAssigningNSEExToException_thenIsAssignable() throws Exception {
assertThat(Exception.class).isAssignableFrom(NoSuchElementException.class);
}
@Test
public void whenComparingWithOffset_thenEquals() throws Exception {
assertThat(5.1).isEqualTo(5, withPrecision(1d));
}
@Test
public void whenCheckingString_then() throws Exception {
assertThat("".isEmpty()).isTrue();
}
@Test
public void whenCheckingFile_then() throws Exception {
final File someFile = File.createTempFile("aaa", "bbb");
someFile.deleteOnExit();
assertThat(someFile).exists().isFile().canRead().canWrite();
}
@Test
public void whenCheckingIS_then() throws Exception {
InputStream given = new ByteArrayInputStream("foo".getBytes());
InputStream expected = new ByteArrayInputStream("foo".getBytes());
assertThat(given).hasSameContentAs(expected);
}
@Test
public void whenGivenMap_then() throws Exception {
Map<Integer, String> map = Maps.newHashMap(2, "a");
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
}
@Test
public void whenGivenException_then() throws Exception {
Exception ex = new Exception("abc");
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
}
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
@Test
public void whenRunningAssertion_thenDescribed() throws Exception {
Person person = new Person("Alex", 34);
assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100);
}
}

View File

@@ -1,96 +0,0 @@
package com.baeldung.testing.assertj;
import com.google.common.base.Optional;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Range;
import com.google.common.collect.Table;
import com.google.common.collect.TreeRangeMap;
import com.google.common.io.Files;
import org.assertj.guava.data.MapEntry;
import org.junit.Test;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import static org.assertj.guava.api.Assertions.assertThat;
import static org.assertj.guava.api.Assertions.entry;
public class AssertJGuavaUnitTest {
@Test
public void givenTwoEmptyFiles_whenComparingContent_thenEqual() throws Exception {
final File temp1 = File.createTempFile("bael", "dung1");
final File temp2 = File.createTempFile("bael", "dung2");
assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
}
@Test
public void givenMultimap_whenVerifying_thenCorrect() throws Exception {
final Multimap<Integer, String> mmap = ArrayListMultimap.create();
mmap.put(1, "one");
mmap.put(1, "1");
assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
}
@Test
public void givenMultimaps_whenVerifyingContent_thenCorrect() throws Exception {
final Multimap<Integer, String> mmap1 = ArrayListMultimap.create();
mmap1.put(1, "one");
mmap1.put(1, "1");
mmap1.put(2, "two");
mmap1.put(2, "2");
final Multimap<Integer, String> mmap1_clone = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
mmap1_clone.put(1, "one");
mmap1_clone.put(1, "1");
mmap1_clone.put(2, "two");
mmap1_clone.put(2, "2");
final Multimap<Integer, String> mmap2 = Multimaps.newSetMultimap(new HashMap<>(), HashSet::new);
mmap2.put(1, "one");
mmap2.put(1, "1");
assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
}
@Test
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
final Optional<String> something = Optional.of("something");
assertThat(something).isPresent().extractingValue().isEqualTo("something");
}
@Test
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
final Range<String> range = Range.openClosed("a", "g");
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
}
@Test
public void givenRangeMap_whenVerifying_thenShouldBeCorrect() throws Exception {
final TreeRangeMap<Integer, String> map = TreeRangeMap.create();
map.put(Range.closed(0, 60), "F");
map.put(Range.closed(61, 70), "D");
assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
}
@Test
public void givenTable_whenVerifying_thenShouldBeCorrect() throws Exception {
final Table<Integer, String, String> table = HashBasedTable.create(2, 2);
table.put(1, "A", "PRESENT");
table.put(1, "B", "ABSENT");
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
}
}

View File

@@ -1,108 +0,0 @@
package com.baeldung.testing.assertj;
import org.junit.Test;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import static java.time.LocalDate.ofYearDay;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class AssertJJava8UnitTest {
@Test
public void givenOptional_shouldAssert() throws Exception {
final Optional<String> givenOptional = Optional.of("something");
assertThat(givenOptional).isPresent().hasValue("something");
}
@Test
public void givenPredicate_shouldAssert() throws Exception {
final Predicate<String> predicate = s -> s.length() > 4;
assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
}
@Test
public void givenLocalDate_shouldAssert() throws Exception {
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
final LocalDate todayDate = LocalDate.now();
assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
}
@Test
public void givenLocalDateTime_shouldAssert() throws Exception {
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
}
@Test
public void givenLocalTime_shouldAssert() throws Exception {
final LocalTime givenLocalTime = LocalTime.of(12, 15);
assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
}
@Test
public void givenList_shouldAssertFlatExtracting() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
}
@Test
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
}
@Test
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
}
@Test
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
}
@Test
public void givenString_shouldSatisfy() throws Exception {
final String givenString = "someString";
assertThat(givenString).satisfies(s -> {
assertThat(s).isNotEmpty();
assertThat(s).hasSize(10);
});
}
@Test
public void givenString_shouldMatch() throws Exception {
final String emptyString = "";
assertThat(emptyString).matches(String::isEmpty);
}
@Test
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
final List<String> givenList = Arrays.asList("");
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
}
}

View File

@@ -1,44 +0,0 @@
package com.baeldung.testing.assertj.custom;
import static com.baeldung.testing.assertj.custom.Assertions.assertThat;
import static org.junit.Assert.fail;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class AssertJCustomAssertionsUnitTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void whenPersonNameMatches_thenCorrect() {
Person person = new Person("John Doe", 20);
assertThat(person).hasFullName("John Doe");
}
@Test
public void whenPersonAgeLessThanEighteen_thenNotAdult() {
Person person = new Person("Jane Roe", 16);
try {
assertThat(person).isAdult();
fail();
} catch (AssertionError e) {
org.assertj.core.api.Assertions.assertThat(e).hasMessage("Expected person to be adult");
}
}
@Test
public void whenPersonDoesNotHaveAMatchingNickname_thenIncorrect() {
Person person = new Person("John Doe", 20);
person.addNickname("Nick");
try {
assertThat(person).hasNickname("John");
fail();
} catch (AssertionError e) {
org.assertj.core.api.Assertions.assertThat(e).hasMessage("Expected person to have nickname John");
}
}
}

View File

@@ -1,9 +0,0 @@
package com.baeldung.testing.assertj.custom;
public class Assertions {
public static PersonAssert assertThat(Person actual) {
return new PersonAssert(actual);
}
// static factory methods of other assertion classes
}

View File

@@ -1,38 +0,0 @@
package com.baeldung.testing.assertj.custom;
import org.assertj.core.api.AbstractAssert;
public class PersonAssert extends AbstractAssert<PersonAssert, Person> {
public PersonAssert(Person actual) {
super(actual, PersonAssert.class);
}
public static PersonAssert assertThat(Person actual) {
return new PersonAssert(actual);
}
public PersonAssert hasFullName(String fullName) {
isNotNull();
if (!actual.getFullName().equals(fullName)) {
failWithMessage("Expected person to have full name %s but was %s", fullName, actual.getFullName());
}
return this;
}
public PersonAssert isAdult() {
isNotNull();
if (actual.getAge() < 18) {
failWithMessage("Expected person to be adult");
}
return this;
}
public PersonAssert hasNickname(String nickName) {
isNotNull();
if (!actual.getNicknames().contains(nickName)) {
failWithMessage("Expected person to have nickname %s", nickName);
}
return this;
}
}

View File

@@ -1,24 +0,0 @@
package com.baeldung.testing.assertj.exceptions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import org.junit.Test;
public class Java7StyleAssertions {
@Test
public void whenDividingByZero_thenArithmeticException() {
try {
int numerator = 10;
int denominator = 0;
int quotient = numerator / denominator;
fail("ArithmeticException expected because dividing by zero yields an ArithmeticException.");
failBecauseExceptionWasNotThrown(ArithmeticException.class);
} catch (Exception e) {
assertThat(e).hasMessage("/ by zero");
assertThat(e).isInstanceOf(ArithmeticException.class);
}
}
}

View File

@@ -1,66 +0,0 @@
package com.baeldung.testing.assertj.exceptions;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.catchThrowable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
public class Java8StyleAssertions {
@Test
public void whenGettingOutOfBoundsItem_thenIndexOutOfBoundsException() {
assertThatThrownBy(() -> {
ArrayList<String> myStringList = new ArrayList<String>(Arrays.asList("Strine one", "String two"));
myStringList.get(2);
}).isInstanceOf(IndexOutOfBoundsException.class)
.hasMessageStartingWith("Index: 2")
.hasMessageContaining("2")
.hasMessageEndingWith("Size: 2")
.hasMessageContaining("Index: 2, Size: 2")
.hasMessage("Index: %s, Size: %s", 2, 2)
.hasMessageMatching("Index: \\d+, Size: \\d+")
.hasNoCause();
}
@Test
public void whenWrappingException_thenCauseInstanceOfWrappedExceptionType() {
assertThatThrownBy(() -> {
try {
throw new IOException();
} catch (IOException e) {
throw new RuntimeException(e);
}
}).isInstanceOf(RuntimeException.class)
.hasCauseInstanceOf(IOException.class)
.hasStackTraceContaining("IOException");
}
@Test
public void whenDividingByZero_thenArithmeticException() {
assertThatExceptionOfType(ArithmeticException.class).isThrownBy(() -> {
int numerator = 10;
int denominator = 0;
int quotient = numerator / denominator;
})
.withMessageContaining("/ by zero");
// Alternatively:
// when
Throwable thrown = catchThrowable(() -> {
int numerator = 10;
int denominator = 0;
int quotient = numerator / denominator;
});
// then
assertThat(thrown).isInstanceOf(ArithmeticException.class)
.hasMessageContaining("/ by zero");
}
}

View File

@@ -1,14 +0,0 @@
package com.baeldung.testing.calculator;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(
features = {"classpath:features/calculator.feature", "classpath:features/calculator-scenario-outline.feature"}
, plugin = {"pretty", "json:target/reports/json/calculator.json"}
, glue = {"com.baeldung.cucumber.calculator"}
)
public class CalculatorIntegrationTest {
}

View File

@@ -1,38 +0,0 @@
package com.baeldung.testing.calculator;
import com.baeldung.cucumber.Calculator;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.hamcrest.Matchers;
import org.junit.Assert;
public class CalculatorRunSteps {
private int total;
private Calculator calculator;
@Before
private void init() {
total = -999;
}
@Given("^I have a calculator$")
public void initializeCalculator() throws Throwable {
calculator = new Calculator();
}
@When("^I add (-?\\d+) and (-?\\d+)$")
public void testAdd(int num1, int num2) throws Throwable {
total = calculator.add(num1, num2);
}
@Then("^the result should be (-?\\d+)$")
public void validateResult(int result) throws Throwable {
Assert.assertThat(total, Matchers.equalTo(result));
}
}

View File

@@ -1,93 +0,0 @@
package com.baeldung.testing.jgotesting;
import java.io.File;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.is;
import org.jgotesting.rule.JGoTestRule;
import static org.jgotesting.Assert.*; // same methods as org.junit.Assert.*
import static org.jgotesting.Check.*; // ditto, with different names
import static org.jgotesting.Testing.*;
import org.jgotesting.Checker;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
public class JGoTestingUnitTest {
@Rule
public final JGoTestRule test = new JGoTestRule();
@Test
public void whenComparingIntegers_thenEqual() {
int anInt = 10;
assertEquals(anInt, 10);
checkEquals(anInt, 10);
}
@Ignore
@Test
public void whenComparingNumbers_thenLoggedMessage() {
log("There was something wrong when comparing numbers");
int anInt = 10;
int anotherInt = 10;
checkEquals(anInt, 10);
checkTrue("First number should be bigger", 10 > anotherInt);
checkSame(anInt, anotherInt);
}
@Ignore
@Test
public void whenComparingNumbers_thenFormattedMessage() {
int anInt = 10;
int anotherInt = 10;
logf("There was something wrong when comparing numbers %d and %d", anInt, anotherInt);
checkEquals(anInt, 10);
checkTrue("First number should be bigger", 10 > anotherInt);
checkSame(anInt, anotherInt);
}
@Test
public void whenComparingStrings_thenMultipleAssertions() {
String aString = "This is a string";
String anotherString = "This Is A String";
test.check(aString, equalToIgnoringCase(anotherString))
.check(aString.length() == 16)
.check(aString.startsWith("This"));
}
@Ignore
@Test
public void whenComparingStrings_thenMultipleFailingAssertions() {
String aString = "the test string";
String anotherString = "The Test String";
checkEquals("Strings are not equal!", aString, anotherString);
checkTrue("String is longer than one character", aString.length() == 1);
checkSame("Strings are not the same", aString, anotherString);
}
@Ignore
@Test
public void givenFile_whenDoesnotExists_thenTerminated() throws Exception {
File aFile = new File("a_dummy_file.txt");
terminateIf(aFile.exists(), is(false));
// This doesn't get executed
checkEquals(aFile.getName(), "a_dummy_file.txt");
}
@Test
public void givenChecker_whenComparingStrings_thenEqual() throws Exception {
Checker<String> aChecker = s -> s.matches("\\d+");
String aString = "1235";
test.check(aString, aChecker);
}
}

View File

@@ -1,12 +0,0 @@
package com.baeldung.testing.shopping;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features = { "classpath:features/shopping.feature" })
public class ShoppingIntegrationTest {
}

View File

@@ -1,22 +0,0 @@
package com.baeldung.testing.shopping;
import static org.junit.Assert.assertEquals;
import cucumber.api.java8.En;
public class ShoppingStepsDef implements En {
private int budget = 0;
public ShoppingStepsDef() {
Given("I have (\\d+) in my wallet", (Integer money) -> budget = money);
When("I buy .* with (\\d+)", (Integer price) -> budget -= price);
Then("I should have (\\d+) in my wallet", (Integer finalBudget) -> {
assertEquals(budget, finalBudget.intValue());
});
}
}

View File

@@ -1,561 +0,0 @@
package com.baeldung.testing.truth;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.collect.Range;
import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import com.google.common.collect.TreeMultiset;
import static com.baeldung.testing.truth.UserSubject.*;
import static com.google.common.truth.Truth.*;
import static com.google.common.truth.Truth8.*;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Ignore;
import org.junit.Test;
public class GoogleTruthUnitTest {
@Test
public void whenComparingInteger_thenEqual() {
int anInt = 10;
assertThat(anInt).isEqualTo(10);
}
@Test
public void whenComparingFloat_thenIsBigger() {
float aFloat = 10.0f;
assertThat(aFloat).isGreaterThan(1.0f);
}
@Test
public void whenComparingDouble_thenIsSmaller() {
double aDouble = 10.0f;
assertThat(aDouble).isLessThan(20.0);
}
@Test
public void whenComparingFloat_thenWithinPrecision() {
float aFloat = 23.04f;
assertThat(aFloat).isWithin(1.3f)
.of(23.3f);
}
@Test
public void whenComparingFloat_thenNotWithinPrecision() {
float aFloat = 23.04f;
assertThat(aFloat).isNotWithin(1.3f)
.of(100f);
}
@Test
public void whenComparingDouble_thenWithinPrecision() {
double aDouble = 22.18;
assertThat(aDouble).isWithin(2)
.of(23d);
}
@Test
public void whenComparingDouble_thenNotWithinPrecision() {
double aDouble = 22.08;
assertThat(aDouble).isNotWithin(2)
.of(100);
}
@Test
public void whenComparingBigDecimal_thenEqualIgnoringScale() {
BigDecimal aBigDecimal = BigDecimal.valueOf(1000, 3);
assertThat(aBigDecimal).isEqualToIgnoringScale(new BigDecimal(1.0));
}
@Test
public void whenCheckingBoolean_thenTrue() {
boolean aBoolean = true;
assertThat(aBoolean).isTrue();
}
@Test
public void whenCheckingBoolean_thenFalse() {
boolean aBoolean = false;
assertThat(aBoolean).isFalse();
}
@Test
public void whenComparingArrays_thenEqual() {
String[] firstArrayOfStrings = { "one", "two", "three" };
String[] secondArrayOfStrings = { "one", "two", "three" };
assertThat(firstArrayOfStrings).isEqualTo(secondArrayOfStrings);
}
@Test
public void whenComparingArrays_thenNotEqual() {
String[] firstArrayOfStrings = { "one", "two", "three" };
String[] secondArrayOfStrings = { "three", "two", "one" };
assertThat(firstArrayOfStrings).isNotEqualTo(secondArrayOfStrings);
}
@Test
public void whenCheckingArray_thenEmpty() {
Object[] anArray = {};
assertThat(anArray).isEmpty();
}
@Test
public void whenCheckingArray_thenNotEmpty() {
String[] arrayOfStrings = { "One String " };
assertThat(arrayOfStrings).isNotEmpty();
}
@Test
public void whenCheckingArrayOfDoubles_thenWithinPrecision() {
double[] arrayOfDoubles = { 1, 2, 3, 4, 5 };
assertThat(arrayOfDoubles).hasValuesWithin(5)
.of(6, 7, 8, 9, 10);
}
@Test
public void whenComparingUsers_thenEqual() {
User aUser = new User("John Doe");
User anotherUser = new User("John Doe");
assertThat(aUser).isEqualTo(anotherUser);
}
@Test
public void whenComparingUser_thenIsNull() {
User aUser = null;
assertThat(aUser).isNull();
}
@Test
public void whenComparingUser_thenNotNull() {
User aUser = new User();
assertThat(aUser).isNotNull();
}
@Test
public void whenComparingUser_thenInstanceOf() {
User aUser = new User();
assertThat(aUser).isInstanceOf(User.class);
}
@Test
public void whenComparingUser_thenInList() {
User aUser = new User();
assertThat(aUser).isIn(Arrays.asList(1, 3, aUser, null));
}
@Test
public void whenComparingUser_thenNotInList() {
User aUser = new User();
assertThat(aUser).isNotIn(Arrays.asList(1, 3, "Three"));
}
@Test
public void whenComparingNullUser_thenInList() {
User aUser = null;
User anotherUser = new User();
assertThat(aUser).isIn(Arrays.asList(1, 3, anotherUser, null));
}
@Test
public void whenCheckingString_thenStartsWithString() {
String aString = "This is a string";
assertThat(aString).startsWith("This");
}
@Test
public void whenCheckingString_thenContainsString() {
String aString = "This is a string";
assertThat(aString).contains("is a");
}
@Test
public void whenCheckingString_thenEndsWithString() {
String aString = "This is a string";
assertThat(aString).endsWith("string");
}
@Test
public void whenCheckingString_thenExpectedLength() {
String aString = "This is a string";
assertThat(aString).hasLength(16);
}
@Test
public void whenCheckingString_thenEmpty() {
String aString = "";
assertThat(aString).isEmpty();
}
@Test
public void whenCheckingString_thenMatches() {
String aString = "The string to match";
assertThat(aString).matches(Pattern.compile("[a-zA-Z\\s]+"));
}
@Test
public void whenCheckingComparable_thenAtLeast() {
Comparable<Integer> aComparable = 5;
assertThat(aComparable).isAtLeast(1);
}
@Test
public void whenCheckingComparable_thenAtMost() {
Comparable<Integer> aComparable = 5;
assertThat(aComparable).isAtMost(10);
}
@Test
public void whenCheckingComparable_thenInList() {
Comparable<Integer> aComparable = 5;
assertThat(aComparable).isIn(Arrays.asList(4, 5, 6));
}
@Test
public void whenCheckingComparable_thenInRange() {
Comparable<Integer> aComparable = 5;
assertThat(aComparable).isIn(Range.closed(1, 10));
}
@Test
public void whenCheckingComparable_thenNotInRange() {
Comparable<Integer> aComparable = 5;
assertThat(aComparable).isNotIn(Range.closed(10, 15));
}
@Test
public void whenComparingUsers_thenEquivalent() {
User aUser = new User();
aUser.setName("John Doe");
User anotherUser = new User();
anotherUser.setName("john doe");
assertThat(aUser).isEquivalentAccordingToCompareTo(anotherUser);
}
@Test
public void whenCheckingIterable_thenContains() {
List<Integer> aList = Arrays.asList(4, 5, 6);
assertThat(aList).contains(5);
}
@Test
public void whenCheckingIterable_thenDoesNotContains() {
List<Integer> aList = Arrays.asList(4, 5, 6);
assertThat(aList).doesNotContain(9);
}
@Test
public void whenCheckingIterable_thenContainsAny() {
List<Integer> aList = Arrays.asList(4, 5, 6);
assertThat(aList).containsAnyOf(0, 5, 10);
}
@Test
public void whenCheckingIterable_thenContainsAnyInList() {
List<Integer> aList = Arrays.asList(1, 2, 3);
assertThat(aList).containsAnyIn(Arrays.asList(1, 5, 10));
}
@Test
public void whenCheckingIterable_thenNoDuplicates() {
List<Integer> aList = Arrays.asList(-2, -1, 0, 1, 2);
assertThat(aList).containsNoDuplicates();
}
@Test
public void whenCheckingIterable_thenContainsNoneOf() {
List<Integer> aList = Arrays.asList(4, 5, 6);
assertThat(aList).containsNoneOf(9, 8, 7);
}
@Test
public void whenCheckingIterable_thenContainsNoneIn() {
List<Integer> aList = Arrays.asList(4, 5, 6);
assertThat(aList).containsNoneIn(Arrays.asList(9, 10, 11));
}
@Test
public void whenCheckingIterable_thenContainsExactElements() {
List<String> aList = Arrays.asList("10", "20", "30");
List<String> anotherList = Arrays.asList("10", "20", "30");
assertThat(aList).containsExactlyElementsIn(anotherList)
.inOrder();
}
@Test
public void whenCheckingIterable_thenOrdered() {
Set<String> aSet = new LinkedHashSet<>(Arrays.asList("one", "three", "two"));
assertThat(aSet).isOrdered();
}
@Test
public void givenComparator_whenCheckingIterable_thenOrdered() {
Comparator<String> aComparator = (a, b) -> new Float(a).compareTo(new Float(b));
List<String> aList = Arrays.asList("1", "012", "0020", "100");
assertThat(aList).isOrdered(aComparator);
}
@Test
public void whenCheckingMap_thenContainsEntry() {
Map<String, Object> aMap = new HashMap<>();
aMap.put("one", 1L);
assertThat(aMap).containsEntry("one", 1L);
}
@Test
public void whenCheckingMap_thenContainsKey() {
Map<String, Object> map = new HashMap<>();
map.put("one", 1L);
assertThat(map).containsKey("one");
}
@Test
public void whenCheckingMap_thenContainsEntries() {
Map<String, Object> aMap = new HashMap<>();
aMap.put("first", 1L);
aMap.put("second", 2.0);
aMap.put("third", 3f);
Map<String, Object> anotherMap = new HashMap<>(aMap);
assertThat(aMap).containsExactlyEntriesIn(anotherMap);
}
@Test
public void whenCheckingException_thenInstanceOf() {
Exception anException = new IllegalArgumentException(new NumberFormatException());
assertThat(anException).hasCauseThat()
.isInstanceOf(NumberFormatException.class);
}
@Test
public void whenCheckingException_thenCauseMessageIsKnown() {
Exception anException = new IllegalArgumentException("Bad value");
assertThat(anException).hasMessageThat()
.startsWith("Bad");
}
@Test
public void whenCheckingClass_thenIsAssignable() {
Class<Double> aClass = Double.class;
assertThat(aClass).isAssignableTo(Number.class);
}
// Java 8 Tests
@Test
public void whenCheckingJavaOptional_thenHasValue() {
Optional<Integer> anOptional = Optional.of(1);
assertThat(anOptional).hasValue(1);
}
@Test
public void whenCheckingJavaOptional_thenPresent() {
Optional<String> anOptional = Optional.of("Baeldung");
assertThat(anOptional).isPresent();
}
@Test
public void whenCheckingJavaOptional_thenEmpty() {
Optional anOptional = Optional.empty();
assertThat(anOptional).isEmpty();
}
@Test
public void whenCheckingStream_thenContainsInOrder() {
Stream<Integer> anStream = Stream.of(1, 2, 3);
assertThat(anStream).containsAllOf(1, 2, 3)
.inOrder();
}
@Test
public void whenCheckingStream_thenDoesNotContain() {
Stream<Integer> anStream = IntStream.range(1, 100)
.boxed();
assertThat(anStream).doesNotContain(0);
}
// Guava Tests
@Test
public void whenCheckingGuavaOptional_thenIsAbsent() {
com.google.common.base.Optional anOptional = com.google.common.base.Optional.absent();
assertThat(anOptional).isAbsent();
}
@Test
public void whenCheckingGuavaMultimap_thenExpectedSize() {
Multimap<String, Object> aMultimap = ArrayListMultimap.create();
aMultimap.put("one", 1L);
aMultimap.put("one", 2.0);
assertThat(aMultimap).valuesForKey("one")
.hasSize(2);
}
@Test
public void whenCheckingGuavaMultiset_thenExpectedCount() {
TreeMultiset<String> aMultiset = TreeMultiset.create();
aMultiset.add("baeldung", 10);
assertThat(aMultiset).hasCount("baeldung", 10);
}
@Test
public void whenCheckingGuavaTable_thenContains() {
Table<String, String, String> aTable = getDummyGuavaTable();
assertThat(aTable).contains("firstRow", "firstColumn");
}
@Test
public void whenCheckingGuavaTable_thenContainsCell() {
Table<String, String, String> aTable = getDummyGuavaTable();
assertThat(aTable).containsCell("firstRow", "firstColumn", "baeldung");
}
@Test
public void whenCheckingGuavaTable_thenContainsRow() {
Table<String, String, String> aTable = getDummyGuavaTable();
assertThat(aTable).containsRow("firstRow");
}
@Test
public void whenCheckingGuavaTable_thenContainsColumn() {
Table<String, String, String> aTable = getDummyGuavaTable();
assertThat(aTable).containsColumn("firstColumn");
}
@Test
public void whenCheckingGuavaTable_thenContainsValue() {
Table<String, String, String> aTable = getDummyGuavaTable();
assertThat(aTable).containsValue("baeldung");
}
@Ignore
@Test
public void whenFailingAssertion_thenMessagePrefix() {
User aUser = new User();
assertThat(aUser).named("User [%s]", aUser.getName())
.isNull();
}
@Ignore
@Test
public void whenFailingAssertion_thenCustomMessage() {
User aUser = new User();
assertWithMessage("TEST-985: Secret user subject was NOT null!").that(aUser)
.isNull();
}
@Ignore
@Test
public void whenFailingAssertion_thenCustomMessageAndPrefix() {
User aUser = new User();
assertWithMessage("TEST-985: Secret user subject was NOT null!").that(aUser)
.named("User [%s]", aUser.getName())
.isNull();
}
private Table<String, String, String> getDummyGuavaTable() {
Table<String, String, String> aTable = TreeBasedTable.create();
aTable.put("firstRow", "firstColumn", "baeldung");
return aTable;
}
// Custom User type
@Test
public void whenCheckingUser_thenHasName() {
User aUser = new User();
assertThat(aUser).hasName("John Doe");
}
@Test
public void whenCheckingUser_thenHasNameIgnoringCase() {
User aUser = new User();
assertThat(aUser).hasNameIgnoringCase("john doe");
}
@Test
public void givenUser_whenCheckingEmails_thenExpectedSize() {
User aUser = new User();
assertThat(aUser).emails()
.hasSize(2);
}
}

View File

@@ -1,16 +0,0 @@
Feature: Calculator
As a user
I want to use a calculator to add numbers
So that I don't need to add myself
Scenario Outline: Add two numbers <num1> & <num2>
Given I have a calculator
When I add <num1> and <num2>
Then the result should be <total>
Examples:
| num1 | num2 | total |
| -2 | 3 | 1 |
| 10 | 15 | 25 |
| 99 | -99 | 0 |
| -1 | -10 | -11 |

View File

@@ -1,24 +0,0 @@
Feature: Calculator
As a user
I want to use a calculator to add numbers
So that I don't need to add myself
Scenario: Add two numbers -2 & 3
Given I have a calculator
When I add -2 and 3
Then the result should be 1
Scenario: Add two numbers 10 & 15
Given I have a calculator
When I add 10 and 15
Then the result should be 25
Scenario: Add two numbers 99 & -99
Given I have a calculator
When I add 99 and -99
Then the result should be 0
Scenario: Add two numbers -1 & -10
Given I have a calculator
When I add -1 and -10
Then the result should be -11

View File

@@ -1,11 +0,0 @@
Feature: Shopping
Scenario: Track my budget
Given I have 100 in my wallet
When I buy milk with 10
Then I should have 90 in my wallet
Scenario: Track my budget
Given I have 200 in my wallet
When I buy rice with 20
Then I should have 180 in my wallet

View File

@@ -1,48 +1,48 @@
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>testng</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>testng</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<!-- test scoped -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>testng</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
<properties>
<!-- testing -->
<testng.version>6.10</testng.version>
</properties>
<?xml version="1.0" encoding="UTF-8"?>
<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>
<artifactId>testng</artifactId>
<version>0.1.0-SNAPSHOT</version>
<name>testng</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<!-- test scoped -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>${testng.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>testng</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
</build>
<properties>
<!-- testing -->
<testng.version>6.10</testng.version>
</properties>
</project>

View File

@@ -1,67 +1,67 @@
package com.baeldung.reports;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class CustomisedListener implements ITestListener {
private static final Logger LOGGER = LoggerFactory.getLogger("CUSTOM_LOGS");
@Override
public void onFinish(ITestContext context) {
LOGGER.info("PASSED TEST CASES");
context.getPassedTests()
.getAllResults()
.forEach(result -> {
LOGGER.info(result.getName());
});
LOGGER.info("FAILED TEST CASES");
context.getFailedTests()
.getAllResults()
.forEach(result -> {
LOGGER.info(result.getName());
});
LOGGER.info("Test completed on: " + context.getEndDate()
.toString());
}
@Override
public void onStart(ITestContext arg0) {
LOGGER.info("Started testing on: " + arg0.getStartDate()
.toString());
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailure(ITestResult arg0) {
LOGGER.info("Failed : " + arg0.getName());
}
@Override
public void onTestSkipped(ITestResult arg0) {
LOGGER.info("Skipped Test: " + arg0.getName());
}
@Override
public void onTestStart(ITestResult arg0) {
LOGGER.info("Testing: " + arg0.getName());
}
@Override
public void onTestSuccess(ITestResult arg0) {
long timeTaken = ((arg0.getEndMillis() - arg0.getStartMillis()));
LOGGER.info("Tested: " + arg0.getName() + " Time taken:" + timeTaken + " ms");
}
}
package com.baeldung.reports;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
public class CustomisedListener implements ITestListener {
private static final Logger LOGGER = LoggerFactory.getLogger("CUSTOM_LOGS");
@Override
public void onFinish(ITestContext context) {
LOGGER.info("PASSED TEST CASES");
context.getPassedTests()
.getAllResults()
.forEach(result -> {
LOGGER.info(result.getName());
});
LOGGER.info("FAILED TEST CASES");
context.getFailedTests()
.getAllResults()
.forEach(result -> {
LOGGER.info(result.getName());
});
LOGGER.info("Test completed on: " + context.getEndDate()
.toString());
}
@Override
public void onStart(ITestContext arg0) {
LOGGER.info("Started testing on: " + arg0.getStartDate()
.toString());
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailure(ITestResult arg0) {
LOGGER.info("Failed : " + arg0.getName());
}
@Override
public void onTestSkipped(ITestResult arg0) {
LOGGER.info("Skipped Test: " + arg0.getName());
}
@Override
public void onTestStart(ITestResult arg0) {
LOGGER.info("Testing: " + arg0.getName());
}
@Override
public void onTestSuccess(ITestResult arg0) {
long timeTaken = ((arg0.getEndMillis() - arg0.getStartMillis()));
LOGGER.info("Tested: " + arg0.getName() + " Time taken:" + timeTaken + " ms");
}
}

View File

@@ -1,111 +1,111 @@
package com.baeldung.reports;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class CustomisedReports implements IReporter {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomisedReports.class);
private static final String ROW_TEMPLATE = "<tr class=\"%s\"><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>";
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
String reportTemplate = initReportTemplate();
final String body = suites
.stream()
.flatMap(suiteToResults())
.collect(Collectors.joining());
saveReportTemplate(outputDirectory, reportTemplate.replaceFirst("</tbody>", String.format("%s</tbody>", body)));
}
private Function<ISuite, Stream<? extends String>> suiteToResults() {
return suite -> suite.getResults().entrySet()
.stream()
.flatMap(resultsToRows(suite));
}
private Function<Map.Entry<String, ISuiteResult>, Stream<? extends String>> resultsToRows(ISuite suite) {
return e -> {
ITestContext testContext = e.getValue().getTestContext();
Set<ITestResult> failedTests = testContext
.getFailedTests()
.getAllResults();
Set<ITestResult> passedTests = testContext
.getPassedTests()
.getAllResults();
Set<ITestResult> skippedTests = testContext
.getSkippedTests()
.getAllResults();
String suiteName = suite.getName();
return Stream
.of(failedTests, passedTests, skippedTests)
.flatMap(results -> generateReportRows(e.getKey(), suiteName, results).stream());
};
}
private List<String> generateReportRows(String testName, String suiteName, Set<ITestResult> allTestResults) {
return allTestResults.stream()
.map(testResultToResultRow(testName, suiteName))
.collect(toList());
}
private Function<ITestResult, String> testResultToResultRow(String testName, String suiteName) {
return testResult -> {
switch (testResult.getStatus()) {
case ITestResult.FAILURE:
return String.format(ROW_TEMPLATE, "danger", suiteName, testName, testResult.getName(), "FAILED", "NA");
case ITestResult.SUCCESS:
return String.format(ROW_TEMPLATE, "success", suiteName, testName, testResult.getName(), "PASSED", String.valueOf(testResult.getEndMillis() - testResult.getStartMillis()));
case ITestResult.SKIP:
return String.format(ROW_TEMPLATE, "warning", suiteName, testName, testResult.getName(), "SKIPPED", "NA");
default:
return "";
}
};
}
private String initReportTemplate() {
String template = null;
byte[] reportTemplate;
try {
reportTemplate = Files.readAllBytes(Paths.get("src/test/resources/reportTemplate.html"));
template = new String(reportTemplate, "UTF-8");
} catch (IOException e) {
LOGGER.error("Problem initializing template", e);
}
return template;
}
private void saveReportTemplate(String outputDirectory, String reportTemplate) {
new File(outputDirectory).mkdirs();
try {
PrintWriter reportWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(outputDirectory, "my-report.html"))));
reportWriter.println(reportTemplate);
reportWriter.flush();
reportWriter.close();
} catch (IOException e) {
LOGGER.error("Problem saving template", e);
}
}
}
package com.baeldung.reports;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.*;
import org.testng.xml.XmlSuite;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class CustomisedReports implements IReporter {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomisedReports.class);
private static final String ROW_TEMPLATE = "<tr class=\"%s\"><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>";
public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
String reportTemplate = initReportTemplate();
final String body = suites
.stream()
.flatMap(suiteToResults())
.collect(Collectors.joining());
saveReportTemplate(outputDirectory, reportTemplate.replaceFirst("</tbody>", String.format("%s</tbody>", body)));
}
private Function<ISuite, Stream<? extends String>> suiteToResults() {
return suite -> suite.getResults().entrySet()
.stream()
.flatMap(resultsToRows(suite));
}
private Function<Map.Entry<String, ISuiteResult>, Stream<? extends String>> resultsToRows(ISuite suite) {
return e -> {
ITestContext testContext = e.getValue().getTestContext();
Set<ITestResult> failedTests = testContext
.getFailedTests()
.getAllResults();
Set<ITestResult> passedTests = testContext
.getPassedTests()
.getAllResults();
Set<ITestResult> skippedTests = testContext
.getSkippedTests()
.getAllResults();
String suiteName = suite.getName();
return Stream
.of(failedTests, passedTests, skippedTests)
.flatMap(results -> generateReportRows(e.getKey(), suiteName, results).stream());
};
}
private List<String> generateReportRows(String testName, String suiteName, Set<ITestResult> allTestResults) {
return allTestResults.stream()
.map(testResultToResultRow(testName, suiteName))
.collect(toList());
}
private Function<ITestResult, String> testResultToResultRow(String testName, String suiteName) {
return testResult -> {
switch (testResult.getStatus()) {
case ITestResult.FAILURE:
return String.format(ROW_TEMPLATE, "danger", suiteName, testName, testResult.getName(), "FAILED", "NA");
case ITestResult.SUCCESS:
return String.format(ROW_TEMPLATE, "success", suiteName, testName, testResult.getName(), "PASSED", String.valueOf(testResult.getEndMillis() - testResult.getStartMillis()));
case ITestResult.SKIP:
return String.format(ROW_TEMPLATE, "warning", suiteName, testName, testResult.getName(), "SKIPPED", "NA");
default:
return "";
}
};
}
private String initReportTemplate() {
String template = null;
byte[] reportTemplate;
try {
reportTemplate = Files.readAllBytes(Paths.get("src/test/resources/reportTemplate.html"));
template = new String(reportTemplate, "UTF-8");
} catch (IOException e) {
LOGGER.error("Problem initializing template", e);
}
return template;
}
private void saveReportTemplate(String outputDirectory, String reportTemplate) {
new File(outputDirectory).mkdirs();
try {
PrintWriter reportWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(outputDirectory, "my-report.html"))));
reportWriter.println(reportTemplate);
reportWriter.flush();
reportWriter.close();
} catch (IOException e) {
LOGGER.error("Problem saving template", e);
}
}
}

View File

@@ -1,19 +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>
<?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>

View File

@@ -1,13 +1,13 @@
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="My test suite">
<listeners>
<listener class-name="com.baeldung.reports.CustomisedListener"></listener>
</listeners>
<test name="numbersXML">
<parameter name="value" value="1"/>
<parameter name="isEven" value="false"/>
<classes>
<class name="com.baeldung.ParametrizedLongRunningUnitTest"/>
</classes>
</test>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="My test suite">
<listeners>
<listener class-name="com.baeldung.reports.CustomisedListener"></listener>
</listeners>
<test name="numbersXML">
<parameter name="value" value="1"/>
<parameter name="isEven" value="false"/>
<classes>
<class name="com.baeldung.ParametrizedLongRunningUnitTest"/>
</classes>
</test>
</suite>

View File

@@ -1,13 +1,13 @@
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="regression_test">
<test name="test groups">
<groups>
<run>
<include name="regression"/>
</run>
</groups>
<classes>
<class name="com.baeldung.SummationServiceIntegrationTest"/>
</classes>
</test>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="regression_test">
<test name="test groups">
<groups>
<run>
<include name="regression"/>
</run>
</groups>
<classes>
<class name="com.baeldung.SummationServiceIntegrationTest"/>
</classes>
</test>
</suite>

View File

@@ -1,17 +1,17 @@
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="regression_test">
<test name="test setup">
<groups>
<run>
<include name="regression"/>
</run>
</groups>
<classes>
<class name="com.baeldung.SummationServiceIntegrationTest">
<methods>
<include name="givenNumbers_sumEquals_thenCorrect"/>
</methods>
</class>
</classes>
</test>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="regression_test">
<test name="test setup">
<groups>
<run>
<include name="regression"/>
</run>
</groups>
<classes>
<class name="com.baeldung.SummationServiceIntegrationTest">
<methods>
<include name="givenNumbers_sumEquals_thenCorrect"/>
</methods>
</class>
</classes>
</test>
</suite>

View File

@@ -1,13 +1,13 @@
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="suite" parallel="classes" thread-count="2">
<listeners>
<listener class-name="com.baeldung.reports.CustomisedReports" />
</listeners>
<test name="test suite">
<classes>
<class name="com.baeldung.RegistrationLongRunningUnitTest" />
<class name="com.baeldung.SignInLongRunningUnitTest" />
<class name="com.baeldung.SimpleLongRunningUnitTest" />
</classes>
</test>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="suite" parallel="classes" thread-count="2">
<listeners>
<listener class-name="com.baeldung.reports.CustomisedReports" />
</listeners>
<test name="test suite">
<classes>
<class name="com.baeldung.RegistrationLongRunningUnitTest" />
<class name="com.baeldung.SignInLongRunningUnitTest" />
<class name="com.baeldung.SimpleLongRunningUnitTest" />
</classes>
</test>
</suite>