Merge branch 'master' into master
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/report-*.json
|
||||
@@ -2,3 +2,4 @@
|
||||
|
||||
- [Introduction to Testing with Spock and Groovy](http://www.baeldung.com/groovy-spock)
|
||||
- [Difference Between Stub, Mock, and Spy in the Spock Framework](https://www.baeldung.com/spock-stub-mock-spy)
|
||||
- [Guide to Spock Extensions](https://www.baeldung.com/spock-extensions)
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<spock-core.version>1.3-RC1-groovy-2.4</spock-core.version>
|
||||
<spock-core.version>1.3-groovy-2.4</spock-core.version>
|
||||
<groovy-all.version>2.4.7</groovy-all.version>
|
||||
<gmavenplus-plugin.version>1.5</gmavenplus-plugin.version>
|
||||
</properties>
|
||||
|
||||
@@ -7,6 +7,16 @@ import spock.lang.Specification
|
||||
class IgnoreIfTest extends Specification {
|
||||
|
||||
@IgnoreIf({System.getProperty("os.name").contains("windows")})
|
||||
def "I won't run on windows"() { }
|
||||
def "I won't run on windows"() {
|
||||
expect:
|
||||
true
|
||||
}
|
||||
|
||||
@IgnoreIf({ os.isWindows() })
|
||||
def "I'm using Spock helper classes to run only on windows"() {
|
||||
expect:
|
||||
true
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -2,7 +2,10 @@ import extensions.TimeoutTest
|
||||
import spock.lang.Issue
|
||||
|
||||
runner {
|
||||
filterStackTrace true
|
||||
|
||||
if (System.getenv("FILTER_STACKTRACE") == null) {
|
||||
filterStackTrace false
|
||||
}
|
||||
|
||||
report {
|
||||
issueNamePrefix 'Bug '
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Get the Path of the /src/test/resources Directory in JUnit](https://www.baeldung.com/junit-src-test-resources-directory-path)
|
||||
@@ -0,0 +1,159 @@
|
||||
<?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>junit-5-configuration</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>junit-5-configuration</name>
|
||||
<description>Intro to JUnit 5 configuration</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-engine</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit.vintage.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-migrationsupport</artifactId>
|
||||
<version>${junit.vintage.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-orm</artifactId>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
<resource>
|
||||
<directory>src/main/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>filtering</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<configuration>
|
||||
<excludes>
|
||||
**/*IntegrationTest.java
|
||||
</excludes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>category</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<groups>com.baeldung.categories.UnitTest</groups>
|
||||
<excludedGroups>com.baeldung.categories.IntegrationTest</excludedGroups>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
<profile>
|
||||
<id>tags</id>
|
||||
<activation>
|
||||
<activeByDefault>false</activeByDefault>
|
||||
</activation>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<groups>UnitTest</groups>
|
||||
<excludedGroups>IntegrationTest</excludedGroups>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<junit.jupiter.version>5.4.2</junit.jupiter.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<junit.vintage.version>5.2.0</junit.vintage.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
<spring.version>5.0.6.RELEASE</spring.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.junit.tags.example;
|
||||
|
||||
public class Employee {
|
||||
private int id;
|
||||
|
||||
private String firstName;
|
||||
|
||||
private String lastName;
|
||||
|
||||
private String address;
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(final int id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getFirstName() {
|
||||
return firstName;
|
||||
}
|
||||
|
||||
public void setFirstName(final String firstName) {
|
||||
this.firstName = firstName;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(final String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(final String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.baeldung.junit.tags.example;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Repository
|
||||
public class EmployeeDAO {
|
||||
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
|
||||
|
||||
private SimpleJdbcInsert simpleJdbcInsert;
|
||||
|
||||
@Autowired
|
||||
public void setDataSource(final DataSource dataSource) {
|
||||
jdbcTemplate = new JdbcTemplate(dataSource);
|
||||
|
||||
namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
|
||||
simpleJdbcInsert = new SimpleJdbcInsert(dataSource).withTableName("EMPLOYEE");
|
||||
|
||||
}
|
||||
|
||||
public int getCountOfEmployees() {
|
||||
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE", Integer.class);
|
||||
}
|
||||
|
||||
public List<Employee> getAllEmployees() {
|
||||
return jdbcTemplate.query("SELECT * FROM EMPLOYEE", new EmployeeRowMapper());
|
||||
}
|
||||
|
||||
public int addEmplyee(final int id) {
|
||||
return jdbcTemplate.update("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", id, "Bill", "Gates", "USA");
|
||||
}
|
||||
|
||||
public int addEmplyeeUsingSimpelJdbcInsert(final Employee emp) {
|
||||
final Map<String, Object> parameters = new HashMap<String, Object>();
|
||||
parameters.put("ID", emp.getId());
|
||||
parameters.put("FIRST_NAME", emp.getFirstName());
|
||||
parameters.put("LAST_NAME", emp.getLastName());
|
||||
parameters.put("ADDRESS", emp.getAddress());
|
||||
|
||||
return simpleJdbcInsert.execute(parameters);
|
||||
}
|
||||
|
||||
// for testing
|
||||
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.junit.tags.example;
|
||||
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class EmployeeRowMapper implements RowMapper<Employee> {
|
||||
|
||||
@Override
|
||||
public Employee mapRow(final ResultSet rs, final int rowNum) throws SQLException {
|
||||
final Employee employee = new Employee();
|
||||
|
||||
employee.setId(rs.getInt("ID"));
|
||||
employee.setFirstName(rs.getString("FIRST_NAME"));
|
||||
employee.setLastName(rs.getString("LAST_NAME"));
|
||||
employee.setAddress(rs.getString("ADDRESS"));
|
||||
|
||||
return employee;
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.junit.tags.example;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
|
||||
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("com.baeldung.junit.tags.example")
|
||||
public class SpringJdbcConfig {
|
||||
|
||||
@Bean
|
||||
public DataSource dataSource() {
|
||||
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).addScript("classpath:jdbc/schema.sql").addScript("classpath:jdbc/test-data.sql").build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE EMPLOYEE
|
||||
(
|
||||
ID int NOT NULL PRIMARY KEY,
|
||||
FIRST_NAME varchar(255),
|
||||
LAST_NAME varchar(255),
|
||||
ADDRESS varchar(255),
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"
|
||||
>
|
||||
|
||||
<bean id="employeeDao" class="org.baeldung.jdbc.EmployeeDAO">
|
||||
<property name="dataSource" ref="dataSource"/>
|
||||
</bean>
|
||||
|
||||
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
|
||||
<property name="driverClassName" value="${jdbc.driverClassName}"/>
|
||||
<property name="url" value="${jdbc.url}"/>
|
||||
<property name="username" value="${jdbc.username}"/>
|
||||
<property name="password" value="${jdbc.password}"/>
|
||||
</bean>
|
||||
|
||||
<context:property-placeholder location="jdbc.properties"/>
|
||||
</beans>
|
||||
@@ -0,0 +1,7 @@
|
||||
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
|
||||
|
||||
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
|
||||
|
||||
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
|
||||
|
||||
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.categories;
|
||||
|
||||
import com.baeldung.junit.tags.example.Employee;
|
||||
import com.baeldung.junit.tags.example.EmployeeDAO;
|
||||
import com.baeldung.junit.tags.example.SpringJdbcConfig;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.experimental.categories.Category;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class EmployeeDAOCategoryIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private EmployeeDAO employeeDao;
|
||||
|
||||
@Mock
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
private EmployeeDAO employeeDAO;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
employeeDAO = new EmployeeDAO();
|
||||
employeeDAO.setJdbcTemplate(jdbcTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Category(IntegrationTest.class)
|
||||
public void testAddEmployeeUsingSimpelJdbcInsert() {
|
||||
final Employee emp = new Employee();
|
||||
emp.setId(12);
|
||||
emp.setFirstName("testFirstName");
|
||||
emp.setLastName("testLastName");
|
||||
emp.setAddress("testAddress");
|
||||
|
||||
Assert.assertEquals(employeeDao.addEmplyeeUsingSimpelJdbcInsert(emp), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Category(UnitTest.class)
|
||||
public void givenNumberOfEmployeeWhenCountEmployeeThenCountMatch() {
|
||||
|
||||
// given
|
||||
Mockito.when(jdbcTemplate.queryForObject(Mockito.any(String.class), Mockito.eq(Integer.class)))
|
||||
.thenReturn(1);
|
||||
|
||||
// when
|
||||
int countOfEmployees = employeeDAO.getCountOfEmployees();
|
||||
|
||||
// then
|
||||
Assert.assertThat(countOfEmployees, CoreMatchers.is(1));
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.categories;
|
||||
|
||||
import org.junit.experimental.categories.Categories;
|
||||
import org.junit.experimental.categories.Categories.IncludeCategory;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.runners.Suite.SuiteClasses;
|
||||
|
||||
@RunWith(Categories.class)
|
||||
@IncludeCategory(UnitTest.class)
|
||||
@SuiteClasses(EmployeeDAOCategoryIntegrationTest.class)
|
||||
public class EmployeeDAOUnitTestSuite {
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.categories;
|
||||
|
||||
public interface IntegrationTest {
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baeldung.categories;
|
||||
|
||||
public interface UnitTest {
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.baeldung.example;
|
||||
|
||||
import com.baeldung.junit.tags.example.Employee;
|
||||
import com.baeldung.junit.tags.example.EmployeeDAO;
|
||||
import com.baeldung.junit.tags.example.SpringJdbcConfig;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class EmployeeDAOIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private EmployeeDAO employeeDao;
|
||||
|
||||
@Test
|
||||
public void testQueryMethod() {
|
||||
Assert.assertEquals(employeeDao.getAllEmployees().size(), 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateMethod() {
|
||||
Assert.assertEquals(employeeDao.addEmplyee(5), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddEmployeeUsingSimpelJdbcInsert() {
|
||||
final Employee emp = new Employee();
|
||||
emp.setId(11);
|
||||
emp.setFirstName("testFirstName");
|
||||
emp.setLastName("testLastName");
|
||||
emp.setAddress("testAddress");
|
||||
|
||||
Assert.assertEquals(employeeDao.addEmplyeeUsingSimpelJdbcInsert(emp), 1);
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.example;
|
||||
|
||||
import com.baeldung.junit.tags.example.EmployeeDAO;
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
|
||||
public class EmployeeUnitTest {
|
||||
|
||||
@Mock
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
|
||||
private EmployeeDAO employeeDAO;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
employeeDAO = new EmployeeDAO();
|
||||
employeeDAO.setJdbcTemplate(jdbcTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNumberOfEmployeeWhenCountEmployeeThenCountMatch() {
|
||||
|
||||
// given
|
||||
Mockito.when(jdbcTemplate.queryForObject(Mockito.any(String.class), Mockito.eq(Integer.class)))
|
||||
.thenReturn(1);
|
||||
|
||||
// when
|
||||
int countOfEmployees = employeeDAO.getCountOfEmployees();
|
||||
|
||||
// then
|
||||
Assert.assertThat(countOfEmployees, CoreMatchers.is(1));
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.resourcedirectory;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
public class ReadResourceDirectoryUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenResourcePath_whenReadAbsolutePathWithFile_thenAbsolutePathEndsWithDirectory() {
|
||||
String path = "src/test/resources";
|
||||
|
||||
File file = new File(path);
|
||||
String absolutePath = file.getAbsolutePath();
|
||||
|
||||
System.out.println(absolutePath);
|
||||
Assert.assertTrue(absolutePath.endsWith("src/test/resources"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourcePath_whenReadAbsolutePathWithPaths_thenAbsolutePathEndsWithDirectory() {
|
||||
Path resourceDirectory = Paths.get("src", "test", "resources");
|
||||
|
||||
String absolutePath = resourceDirectory.toFile().getAbsolutePath();
|
||||
|
||||
System.out.println(absolutePath);
|
||||
Assert.assertTrue(absolutePath.endsWith("src/test/resources"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenResourceFile_whenReadResourceWithClassLoader_thenPathEndWithFilename() {
|
||||
String resourceName = "example_resource.txt";
|
||||
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
File file = new File(classLoader.getResource(resourceName).getFile());
|
||||
String absolutePath = file.getAbsolutePath();
|
||||
|
||||
System.out.println(absolutePath);
|
||||
Assert.assertTrue(absolutePath.endsWith("/example_resource.txt"));
|
||||
}
|
||||
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.tags;
|
||||
|
||||
import com.baeldung.junit.tags.example.Employee;
|
||||
import com.baeldung.junit.tags.example.EmployeeDAO;
|
||||
import com.baeldung.junit.tags.example.SpringJdbcConfig;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Tag;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.context.support.AnnotationConfigContextLoader;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@ContextConfiguration(classes = { SpringJdbcConfig.class }, loader = AnnotationConfigContextLoader.class)
|
||||
public class EmployeeDAOIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
private EmployeeDAO employeeDao;
|
||||
|
||||
@Mock
|
||||
private JdbcTemplate jdbcTemplate;
|
||||
private EmployeeDAO employeeDAO;
|
||||
|
||||
@BeforeEach
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
employeeDAO = new EmployeeDAO();
|
||||
employeeDAO.setJdbcTemplate(jdbcTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("IntegrationTest")
|
||||
public void testAddEmployeeUsingSimpelJdbcInsert() {
|
||||
final Employee emp = new Employee();
|
||||
emp.setId(12);
|
||||
emp.setFirstName("testFirstName");
|
||||
emp.setLastName("testLastName");
|
||||
emp.setAddress("testAddress");
|
||||
|
||||
Assertions.assertEquals(employeeDao.addEmplyeeUsingSimpelJdbcInsert(emp), 1);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Tag("UnitTest")
|
||||
public void givenNumberOfEmployeeWhenCountEmployeeThenCountMatch() {
|
||||
|
||||
// given
|
||||
Mockito.when(jdbcTemplate.queryForObject(Mockito.any(String.class), Mockito.eq(Integer.class)))
|
||||
.thenReturn(1);
|
||||
|
||||
// when
|
||||
int countOfEmployees = employeeDAO.getCountOfEmployees();
|
||||
|
||||
// then
|
||||
Assertions.assertEquals(1, countOfEmployees);
|
||||
}
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.tags;
|
||||
|
||||
import org.junit.platform.runner.JUnitPlatform;
|
||||
import org.junit.platform.suite.api.IncludeTags;
|
||||
import org.junit.platform.suite.api.SelectPackages;
|
||||
import org.junit.runner.RunWith;
|
||||
|
||||
@RunWith(JUnitPlatform.class)
|
||||
@SelectPackages("com.baeldung.tags")
|
||||
@IncludeTags("UnitTest")
|
||||
public class EmployeeDAOTestSuite {
|
||||
}
|
||||
@@ -21,24 +21,34 @@
|
||||
<artifactId>junit-platform-engine</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<version>${junit.vintage.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-migrationsupport</artifactId>
|
||||
<version>${junit.vintage.version}</version>
|
||||
@@ -103,13 +113,6 @@
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
@@ -130,12 +133,11 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit.jupiter.version>5.3.1</junit.jupiter.version>
|
||||
<junit.jupiter.version>5.4.2</junit.jupiter.version>
|
||||
<mockito.junit.jupiter.version>2.23.0</mockito.junit.jupiter.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<junit.vintage.version>5.2.0</junit.vintage.version>
|
||||
<junit.platform.version>1.4.2</junit.platform.version>
|
||||
<junit.vintage.version>5.4.2</junit.vintage.version>
|
||||
<log4j2.version>2.8.2</log4j2.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
<powermock.version>2.0.0-RC.1</powermock.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
|
||||
@@ -2,7 +2,21 @@ package com.baeldung;
|
||||
|
||||
import static java.time.Duration.ofSeconds;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertLinesMatch;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeout;
|
||||
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedList;
|
||||
@@ -91,11 +105,12 @@ public class AssertionUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenMultipleAssertion_whenAssertingAll_thenOK() {
|
||||
Object obj = null;
|
||||
assertAll(
|
||||
"heading",
|
||||
() -> assertEquals(4, 2 * 2, "4 is 2 times 2"),
|
||||
() -> assertEquals("java", "JAVA".toLowerCase()),
|
||||
() -> assertEquals(null, null, "null is equal to null")
|
||||
() -> assertEquals(obj, null, "null is equal to null")
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.junit5.order;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.MethodOrderer.Alphanumeric;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
@TestMethodOrder(Alphanumeric.class)
|
||||
public class AlphanumericOrderUnitTest {
|
||||
private static StringBuilder output = new StringBuilder("");
|
||||
|
||||
@Test
|
||||
public void myATest() {
|
||||
output.append("A");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void myBTest() {
|
||||
output.append("B");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void myaTest() {
|
||||
output.append("a");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
public static void assertOutput() {
|
||||
assertEquals(output.toString(), "ABa");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.junit5.order;
|
||||
|
||||
import org.junit.jupiter.api.MethodDescriptor;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.MethodOrdererContext;
|
||||
|
||||
public class CustomOrder implements MethodOrderer{
|
||||
@Override
|
||||
public void orderMethods(MethodOrdererContext context) {
|
||||
context.getMethodDescriptors().sort((MethodDescriptor m1, MethodDescriptor m2)->m1.getMethod().getName().compareToIgnoreCase(m2.getMethod().getName()));
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.junit5.order;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
@TestMethodOrder(CustomOrder.class)
|
||||
public class CustomOrderUnitTest {
|
||||
private static StringBuilder output = new StringBuilder("");
|
||||
|
||||
@Test
|
||||
public void myATest() {
|
||||
output.append("A");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void myBTest() {
|
||||
output.append("B");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void myaTest() {
|
||||
output.append("a");
|
||||
}
|
||||
|
||||
|
||||
@AfterAll
|
||||
public static void assertOutput() {
|
||||
assertEquals(output.toString(), "AaB");
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.junit5.order;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
@TestMethodOrder(OrderAnnotation.class)
|
||||
public class OrderAnnotationUnitTest {
|
||||
private static StringBuilder output = new StringBuilder("");
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
public void firstTest() {
|
||||
output.append("a");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
public void secondTest() {
|
||||
output.append("b");
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
public void thirdTest() {
|
||||
output.append("c");
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
public static void assertOutput() {
|
||||
assertEquals(output.toString(), "abc");
|
||||
}
|
||||
}
|
||||
@@ -86,7 +86,30 @@ class StringsUnitTest {
|
||||
assertEquals(expected, actualValue);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullSource
|
||||
void isBlank_ShouldReturnTrueForNullInputs(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EmptySource
|
||||
void isBlank_ShouldReturnTrueForEmptyStrings(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
void isBlank_ShouldReturnTrueForNullAndEmptyStrings(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@NullAndEmptySource
|
||||
@ValueSource(strings = {" ", "\t", "\n"})
|
||||
void isBlank_ShouldReturnTrueForAllTypesOfBlankStrings(String input) {
|
||||
assertTrue(Strings.isBlank(input));
|
||||
}
|
||||
|
||||
private static Stream<Arguments> provideStringsForIsBlank() {
|
||||
return Stream.of(
|
||||
|
||||
@@ -2,7 +2,4 @@
|
||||
|
||||
- [Mockito’s Java 8 Features](http://www.baeldung.com/mockito-2-java-8)
|
||||
- [Lazy Verification with Mockito 2](http://www.baeldung.com/mockito-2-lazy-verification)
|
||||
|
||||
## Mockito 2 and Java 8 Tips
|
||||
|
||||
Examples on how to leverage Java 8 new features with Mockito version 2
|
||||
- [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception)
|
||||
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package com.baeldung.mockito.misusing;
|
||||
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.rules.MethodRule;
|
||||
import org.junit.runners.model.FrameworkMethod;
|
||||
import org.junit.runners.model.Statement;
|
||||
|
||||
public class ExpectedTestFailureRule implements MethodRule {
|
||||
|
||||
private final MethodRule testedRule;
|
||||
private FailureAssert failureAssert = null;
|
||||
|
||||
public ExpectedTestFailureRule(MethodRule testedRule) {
|
||||
this.testedRule = testedRule;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
|
||||
return new Statement() {
|
||||
public void evaluate() throws Throwable {
|
||||
try {
|
||||
testedRule.apply(base, method, target)
|
||||
.evaluate();
|
||||
} catch (Throwable t) {
|
||||
if (failureAssert == null) {
|
||||
throw t;
|
||||
}
|
||||
failureAssert.doAssert(t);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public void expectedFailure(final Class<? extends Throwable> expected) {
|
||||
FailureAssert assertion = t -> Assert.assertThat(t, Matchers.isA((Class<Throwable>) expected));
|
||||
this.expectedFailure(assertion);
|
||||
}
|
||||
|
||||
private void expectedFailure(FailureAssert failureAssert) {
|
||||
this.failureAssert = failureAssert;
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface FailureAssert {
|
||||
abstract void doAssert(Throwable t);
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.mockito.misusing;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
public class MockitoUnecessaryStubUnitTest {
|
||||
|
||||
@Rule
|
||||
public ExpectedTestFailureRule rule = new ExpectedTestFailureRule(MockitoJUnit.rule()
|
||||
.strictness(Strictness.STRICT_STUBS));
|
||||
|
||||
@Mock
|
||||
private ArrayList<String> mockList;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnusedStub_whenInvokingGetThenThrowUnnecessaryStubbingException() {
|
||||
rule.expectedFailure(UnnecessaryStubbingException.class);
|
||||
|
||||
when(mockList.add("one")).thenReturn(true);
|
||||
when(mockList.get(anyInt())).thenReturn("hello");
|
||||
|
||||
assertEquals("List should contain hello", "hello", mockList.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLenientdStub_whenInvokingGetThenDontThrowUnnecessaryStubbingException() {
|
||||
lenient().when(mockList.add("one"))
|
||||
.thenReturn(true);
|
||||
when(mockList.get(anyInt())).thenReturn("hello");
|
||||
|
||||
assertEquals("List should contain hello", "hello", mockList.get(1));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -32,5 +32,6 @@
|
||||
<module>test-containers</module>
|
||||
<module>testing</module>
|
||||
<module>testng</module>
|
||||
<module>junit-5-configuration</module>
|
||||
</modules>
|
||||
</project>
|
||||
|
||||
@@ -162,6 +162,11 @@
|
||||
<artifactId>commons-collections</artifactId>
|
||||
<version>${commons-collections.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Rest Assured Dependencies-->
|
||||
<dependency>
|
||||
@@ -179,6 +184,12 @@
|
||||
<artifactId>json-schema-validator</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.scribejava</groupId>
|
||||
<artifactId>scribejava-apis</artifactId>
|
||||
<version>${scribejava.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
@@ -186,8 +197,6 @@
|
||||
<jackson.version>2.9.7</jackson.version>
|
||||
<jackson-coreutils.version>1.8</jackson-coreutils.version>
|
||||
<guava.version>19.0</guava.version>
|
||||
|
||||
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
|
||||
<servlet-api.version>2.5</servlet-api.version>
|
||||
<javax.mail.version>1.4.7</javax.mail.version>
|
||||
<jetty.version>9.4.0.v20161208</jetty.version>
|
||||
@@ -211,6 +220,8 @@
|
||||
|
||||
<rest-assured.version>3.0.1</rest-assured.version>
|
||||
<rest-assured-json-schema-validator.version>3.0.1</rest-assured-json-schema-validator.version>
|
||||
|
||||
<scribejava.version>2.5.3</scribejava.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.restassured.authentication;
|
||||
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.given;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* For this Live Test we need:
|
||||
* * a running instance of the service located in the spring-security-rest-basic-auth module.
|
||||
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-security-rest-basic-auth">spring-security-rest-basic-auth module</a>
|
||||
*
|
||||
*/
|
||||
public class BasicAuthenticationLiveTest {
|
||||
|
||||
private static final String USER = "user1";
|
||||
private static final String PASSWORD = "user1Pass";
|
||||
private static final String SVC_URL = "http://localhost:8080/spring-security-rest-basic-auth/api/foos/1";
|
||||
|
||||
@Test
|
||||
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
|
||||
get(SVC_URL).then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.UNAUTHORIZED.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBasicAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
|
||||
given().auth()
|
||||
.basic(USER, PASSWORD)
|
||||
.when()
|
||||
.get(SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value());
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.restassured.authentication;
|
||||
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* For this Live Test we need:
|
||||
* * a running instance of the service located in the spring-boot-admin/spring-boot-admin-server module.
|
||||
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-boot-admin/spring-boot-admin-server">spring-boot-admin/spring-boot-admin-server module</a>
|
||||
*
|
||||
*/
|
||||
public class BasicPreemtiveAuthenticationLiveTest {
|
||||
|
||||
private static final String USER = "admin";
|
||||
private static final String PASSWORD = "admin";
|
||||
private static final String SVC_URL = "http://localhost:8080/api/applications/";
|
||||
|
||||
@Test
|
||||
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
|
||||
get(SVC_URL).then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.content(containsString("<form"), containsString("action=\"login\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenNonPreemtiveBasicAuthentication_whenRequestSecuredResource_thenLoginPageRetrieved() {
|
||||
given().auth()
|
||||
.basic(USER, PASSWORD)
|
||||
.when()
|
||||
.get(SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.content(containsString("<form"), containsString("action=\"login\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPreemtiveBasicAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
|
||||
given().auth()
|
||||
.preemptive()
|
||||
.basic(USER, PASSWORD)
|
||||
.when()
|
||||
.get(SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.body("size()", is(1));
|
||||
}
|
||||
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.restassured.authentication;
|
||||
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* For this Live Test we need:
|
||||
* * a running instance of the service located in the spring-security-mvc-digest-auth module.
|
||||
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-security-mvc-digest-auth">spring-security-mvc-digest-auth module</a>
|
||||
*
|
||||
*/
|
||||
public class DigestAuthenticationLiveTest {
|
||||
|
||||
private static final String USER = "user1";
|
||||
private static final String PASSWORD = "user1Pass";
|
||||
private static final String SVC_URL = "http://localhost:8080/spring-security-mvc-digest-auth/homepage.html";
|
||||
|
||||
@Test
|
||||
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
|
||||
get(SVC_URL).then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.UNAUTHORIZED.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFormAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
|
||||
given().auth()
|
||||
.digest(USER, PASSWORD)
|
||||
.when()
|
||||
.get(SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.content(containsString("This is the body of the sample view"));
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.restassured.authentication;
|
||||
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.isEmptyString;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import io.restassured.authentication.FormAuthConfig;
|
||||
|
||||
/**
|
||||
* For this Live Test we need:
|
||||
* * a running instance of the service located in the spring-security-mvc-login module.
|
||||
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-security-mvc-login">spring-security-mvc-login module</a>
|
||||
*
|
||||
*/
|
||||
public class FormAuthenticationLiveTest {
|
||||
|
||||
private static final String USER = "user1";
|
||||
private static final String PASSWORD = "user1Pass";
|
||||
private static final String SVC_URL = "http://localhost:8080/spring-security-mvc-login/secured";
|
||||
|
||||
@Test
|
||||
public void givenNoAuthentication_whenRequestSecuredResource_thenLoginFormResponse() {
|
||||
get(SVC_URL).then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.content(containsString("<form"), containsString("action=\"perform_login\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParsingFormAuthentication_whenRequestSecuredResource_thenLoginFormResponse() {
|
||||
// Form can't be parsed correctly because the app is in servlet container, thus the form's 'action' attribute doesn't include the correct URI
|
||||
given().auth()
|
||||
.form(USER, PASSWORD)
|
||||
.when()
|
||||
.get(SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.content(containsString("<form"), containsString("action=\"perform_login\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenFormAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
|
||||
given().auth()
|
||||
.form(USER, PASSWORD, new FormAuthConfig("/spring-security-mvc-login/perform_login", "username", "password"))
|
||||
.when()
|
||||
.get(SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.content(isEmptyString());
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.baeldung.restassured.authentication;
|
||||
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* For this Live Test we need:
|
||||
* * a running instance of the service located in the spring-boot-admin/spring-boot-admin-server module.
|
||||
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-boot-admin/spring-boot-admin-server">spring-boot-admin/spring-boot-admin-server module</a>
|
||||
*
|
||||
*/
|
||||
public class FormAutoconfAuthenticationLiveTest {
|
||||
|
||||
private static final String USER = "admin";
|
||||
private static final String PASSWORD = "admin";
|
||||
private static final String SVC_URL = "http://localhost:8080/ger1/api/applications/";
|
||||
|
||||
@Test
|
||||
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
|
||||
get(SVC_URL).then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.content(containsString("<form"), containsString("action=\"login\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenParsingFormAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
|
||||
given().auth()
|
||||
.form(USER, PASSWORD)
|
||||
.when()
|
||||
.get(SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.body("size()", is(1));
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.restassured.authentication;
|
||||
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
/**
|
||||
* For this Live Test we need:
|
||||
* * a running instance of the authorization server located in the spring-security-oauth repo - oauth-authorization-server module.
|
||||
* @see <a href="https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-authorization-server">spring-security-oauth/oauth-authorization-server module</a>
|
||||
*
|
||||
* * a running instance of the service located in the spring-security-oauth repo - oauth-resource-server-1 module.
|
||||
* @see <a href="https://github.com/Baeldung/spring-security-oauth/tree/master/oauth-resource-server-1">spring-security-oauth/oauth-resource-server-1 module</a>
|
||||
*
|
||||
*/
|
||||
public class OAuth2AuthenticationLiveTest {
|
||||
|
||||
private static final String USER = "john";
|
||||
private static final String PASSWORD = "123";
|
||||
private static final String CLIENT_ID = "fooClientIdPassword";
|
||||
private static final String SECRET = "secret";
|
||||
private static final String AUTH_SVC_TOKEN_URL = "http://localhost:8081/spring-security-oauth-server/oauth/token";
|
||||
private static final String RESOURCE_SVC_URL = "http://localhost:8082/spring-security-oauth-resource/foos/1";
|
||||
|
||||
@Test
|
||||
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
|
||||
get(RESOURCE_SVC_URL).then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.UNAUTHORIZED.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAccessTokenAuthentication_whenRequestSecuredResource_thenResourceRetrieved() {
|
||||
String accessToken = given().auth()
|
||||
.basic(CLIENT_ID, SECRET)
|
||||
.formParam("grant_type", "password")
|
||||
.formParam("username", USER)
|
||||
.formParam("password", PASSWORD)
|
||||
.formParam("scope", "read foo")
|
||||
.when()
|
||||
.post(AUTH_SVC_TOKEN_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.extract()
|
||||
.path("access_token");
|
||||
|
||||
given().auth()
|
||||
.oauth2(accessToken)
|
||||
.when()
|
||||
.get(RESOURCE_SVC_URL)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.body("$", hasKey("id"))
|
||||
.body("$", hasKey("name"));
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.restassured.authentication;
|
||||
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.hasKey;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import io.restassured.http.ContentType;
|
||||
|
||||
/**
|
||||
* For this Live Test we need to obtain a valid Access Token and Token Secret:
|
||||
* * start spring-mvc-simple application in debug mode
|
||||
* @see <a href="https://github.com/eugenp/tutorials/tree/master/spring-mvc-simple">spring-mvc-simple module</a>
|
||||
* * calling localhost:8080/spring-mvc-simple/twitter/authorization/ using the browser
|
||||
* * debug the callback function where we can obtain the fields
|
||||
*/
|
||||
public class OAuthAuthenticationLiveTest {
|
||||
|
||||
// We can obtain these two from the spring-mvc-simple / TwitterController class
|
||||
private static final String OAUTH_API_KEY = "PSRszoHhRDVhyo2RIkThEbWko";
|
||||
private static final String OAUTH_API_SECRET = "prpJbz03DcGRN46sb4ucdSYtVxG8unUKhcnu3an5ItXbEOuenL";
|
||||
private static final String TWITTER_ENDPOINT = "https://api.twitter.com/1.1/account/settings.json";
|
||||
/* We can obtain the following by:
|
||||
* - starting the spring-mvc-simple application
|
||||
* - calling localhost:8080/spring-mvc-simple/twitter/authorization/
|
||||
* - debugging the callback function */
|
||||
private static final String ACCESS_TOKEN = "...";
|
||||
private static final String TOKEN_SECRET = "...";
|
||||
|
||||
@Test
|
||||
public void givenNoAuthentication_whenRequestSecuredResource_thenUnauthorizedResponse() {
|
||||
get(TWITTER_ENDPOINT).then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.BAD_REQUEST.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAccessTokenAuthentication_whenRequestSecuredResource_thenResourceIsRequested() {
|
||||
given().accept(ContentType.JSON)
|
||||
.auth()
|
||||
.oauth(OAUTH_API_KEY, OAUTH_API_SECRET, ACCESS_TOKEN, TOKEN_SECRET)
|
||||
.when()
|
||||
.get(TWITTER_ENDPOINT)
|
||||
.then()
|
||||
.assertThat()
|
||||
.statusCode(HttpStatus.OK.value())
|
||||
.body("$", hasKey("geo_enabled"))
|
||||
.body("$", hasKey("language"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
The "REST With Spring" Classes: http://bit.ly/restwithspring
|
||||
|
||||
### Relevant Articles:
|
||||
- [Test a REST API with Java](http://www.baeldung.com/integration-testing-a-rest-api)
|
||||
- [Introduction to WireMock](http://www.baeldung.com/introduction-to-wiremock)
|
||||
- [Using WireMock Scenarios](https://www.baeldung.com/wiremock-scenarios)
|
||||
- [REST API Testing with Cucumber](http://www.baeldung.com/cucumber-rest-api-testing)
|
||||
|
||||
@@ -149,9 +149,6 @@
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<!-- marshalling -->
|
||||
<jackson.version>2.9.7</jackson.version>
|
||||
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
<commons-lang3.version>3.5</commons-lang3.version>
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
package org.baeldung.rest;
|
||||
|
||||
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.apache.http.entity.ContentType;
|
||||
import org.apache.http.impl.client.HttpClientBuilder;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GithubBasicLiveTest {
|
||||
|
||||
// simple request - response
|
||||
|
||||
@Test
|
||||
public void givenUserDoesNotExists_whenUserInfoIsRetrieved_then404IsReceived() throws ClientProtocolException, IOException {
|
||||
// Given
|
||||
final String name = randomAlphabetic(8);
|
||||
final HttpUriRequest request = new HttpGet("https://api.github.com/users/" + name);
|
||||
|
||||
// When
|
||||
final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
|
||||
|
||||
// Then
|
||||
assertThat(httpResponse.getStatusLine().getStatusCode(), equalTo(HttpStatus.SC_NOT_FOUND));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestWithNoAcceptHeader_whenRequestIsExecuted_thenDefaultResponseContentTypeIsJson() throws ClientProtocolException, IOException {
|
||||
// Given
|
||||
final String jsonMimeType = "application/json";
|
||||
final HttpUriRequest request = new HttpGet("https://api.github.com/users/eugenp");
|
||||
|
||||
// When
|
||||
final HttpResponse response = HttpClientBuilder.create().build().execute(request);
|
||||
|
||||
// Then
|
||||
final String mimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
|
||||
assertEquals(jsonMimeType, mimeType);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUserExists_whenUserInformationIsRetrieved_thenRetrievedResourceIsCorrect() throws ClientProtocolException, IOException {
|
||||
// Given
|
||||
final HttpUriRequest request = new HttpGet("https://api.github.com/users/eugenp");
|
||||
|
||||
// When
|
||||
final HttpResponse response = HttpClientBuilder.create().build().execute(request);
|
||||
|
||||
// Then
|
||||
final GitHubUser resource = RetrieveUtil.retrieveResourceFromResponse(response, GitHubUser.class);
|
||||
assertThat("eugenp", Matchers.is(resource.getLogin()));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -103,7 +103,6 @@
|
||||
<junit.platform.version>1.0.1</junit.platform.version>
|
||||
<junit.vintage.version>4.12.1</junit.vintage.version>
|
||||
<log4j2.version>2.8.2</log4j2.version>
|
||||
<h2.version>1.4.196</h2.version>
|
||||
<mockito.version>2.21.0</mockito.version>
|
||||
<spring.version>5.0.1.RELEASE</spring.version>
|
||||
<testcontainers.version>1.7.2</testcontainers.version>
|
||||
|
||||
Reference in New Issue
Block a user