Merge branch 'master' of https://github.com/eugenp/tutorials
This commit is contained in:
commit
7120a2f1e3
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -1,19 +1,32 @@
|
|||
package com.baeldung.examples.asm.instrumentation;
|
||||
|
||||
import com.baeldung.examples.asm.CustomClassWriter;
|
||||
|
||||
import java.lang.instrument.ClassFileTransformer;
|
||||
import java.lang.instrument.IllegalClassFormatException;
|
||||
import java.lang.instrument.Instrumentation;
|
||||
import java.security.ProtectionDomain;
|
||||
|
||||
/**
|
||||
*
|
||||
* @author baeldung
|
||||
*/
|
||||
public class Premain {
|
||||
|
||||
public static void premain(String agentArgs, Instrumentation inst) {
|
||||
inst.addTransformer((l, name, c, d, b) -> {
|
||||
inst.addTransformer(new ClassFileTransformer() {
|
||||
|
||||
if (name.equals("java/lang/Integer")) {
|
||||
CustomClassWriter cr = new CustomClassWriter(b);
|
||||
return cr.addField();
|
||||
@Override
|
||||
public byte[] transform(ClassLoader l, String name, Class c,
|
||||
ProtectionDomain d, byte[] b)
|
||||
throws IllegalClassFormatException {
|
||||
|
||||
if (name.equals("java/lang/Integer")) {
|
||||
CustomClassWriter cr = new CustomClassWriter(b);
|
||||
return cr.addField();
|
||||
}
|
||||
return b;
|
||||
}
|
||||
return b;
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1,48 @@
|
|||
package com.baeldung.staticdemo;
|
||||
|
||||
/**
|
||||
* This class demonstrates the use of static fields and static methods
|
||||
* the instance variables engine and displacement are distinct for
|
||||
* each and every object whereas static/class variable numberOfCars
|
||||
* is unique and is shared across all objects of this class.
|
||||
*
|
||||
* @author baeldung
|
||||
*
|
||||
*/
|
||||
public class Car {
|
||||
private String name;
|
||||
private String engine;
|
||||
|
||||
public static int numberOfCars;
|
||||
|
||||
public Car(String name, String engine) {
|
||||
this.name = name;
|
||||
this.engine = engine;
|
||||
numberOfCars++;
|
||||
}
|
||||
|
||||
//getters and setters
|
||||
public static int getNumberOfCars() {
|
||||
return numberOfCars;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getEngine() {
|
||||
return engine;
|
||||
}
|
||||
|
||||
public void setEngine(String engine) {
|
||||
this.engine = engine;
|
||||
}
|
||||
|
||||
public static void setNumberOfCars(int numberOfCars) {
|
||||
Car.numberOfCars = numberOfCars;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package com.baeldung.staticdemo;
|
||||
|
||||
public class Singleton {
|
||||
private Singleton() {}
|
||||
|
||||
private static class SingletonHolder {
|
||||
public static final Singleton instance = new Singleton();
|
||||
}
|
||||
|
||||
public static Singleton getInstance() {
|
||||
return SingletonHolder.instance;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.staticdemo;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class StaticBlock {
|
||||
private static List<String> ranks = new LinkedList<>();
|
||||
|
||||
static {
|
||||
ranks.add("Lieutenant");
|
||||
ranks.add("Captain");
|
||||
ranks.add("Major");
|
||||
}
|
||||
|
||||
static {
|
||||
ranks.add("Colonel");
|
||||
ranks.add("General");
|
||||
}
|
||||
|
||||
//getters and setters
|
||||
public static List<String> getRanks() {
|
||||
return ranks;
|
||||
}
|
||||
|
||||
public static void setRanks(List<String> ranks) {
|
||||
StaticBlock.ranks = ranks;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
package com.baeldung.staticdemo;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class CarIntegrationTest {
|
||||
@Test
|
||||
public void whenNumberOfCarObjectsInitialized_thenStaticCounterIncreases() {
|
||||
new Car("Jaguar", "V8");
|
||||
new Car("Bugatti", "W16");
|
||||
assertEquals(2, Car.numberOfCars);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
package com.baeldung.staticdemo;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class SingletonIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void givenStaticInnerClass_whenMultipleTimesInstanceCalled_thenOnlyOneTimeInitialized() {
|
||||
Singleton object1 = Singleton.getInstance();
|
||||
Singleton object2 = Singleton.getInstance();
|
||||
|
||||
Assert.assertSame(object1, object2);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.staticdemo;
|
||||
|
||||
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
|
||||
import static org.junit.Assert.assertThat;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class StaticBlockIntegrationTest {
|
||||
|
||||
@Test
|
||||
public void whenAddedListElementsThroughStaticBlock_thenEnsureCorrectOrder() {
|
||||
List<String> actualList = StaticBlock.getRanks();
|
||||
assertThat(actualList, contains("Lieutenant", "Captain", "Major", "Colonel", "General"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1,38 @@
|
|||
<?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>drools-backward-chaining</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>drools-backward-chaining</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<runtime.version>6.4.0.Final</runtime.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.kie</groupId>
|
||||
<artifactId>kie-api</artifactId>
|
||||
<version>${runtime.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.drools</groupId>
|
||||
<artifactId>drools-core</artifactId>
|
||||
<version>${runtime.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.drools</groupId>
|
||||
<artifactId>drools-decisiontables</artifactId>
|
||||
<version>${runtime.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.kie.api.KieServices;
|
||||
import org.kie.api.runtime.KieContainer;
|
||||
import org.kie.api.runtime.KieSession;
|
||||
|
||||
import com.baeldung.model.Beatle;
|
||||
|
||||
public class BackwardChainingBeatles {
|
||||
public static void main(String[] args) {
|
||||
|
||||
KieServices ks = KieServices.Factory.get();
|
||||
KieContainer kContainer = ks.getKieClasspathContainer();
|
||||
KieSession kSession = kContainer.newKieSession("ksession-backward-chaining");
|
||||
// drools session base on the xml configuration (<strong>kmodule.xml</strong>)
|
||||
|
||||
// graph population
|
||||
kSession.insert(new Beatle("Starr", "drums"));
|
||||
kSession.insert(new Beatle("McCartney", "bass"));
|
||||
kSession.insert(new Beatle("Lennon", "guitar"));
|
||||
kSession.insert(new Beatle("Harrison", "guitar"));
|
||||
|
||||
kSession.insert("Ringo"); // invoke the rule that calls the query implentation of backward chaining
|
||||
kSession.fireAllRules(); // invoke all the rules
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,33 @@
|
|||
package com.baeldung.model;
|
||||
|
||||
import org.kie.api.definition.type.Position;
|
||||
|
||||
public class Beatle {
|
||||
|
||||
@Position(0)
|
||||
private String lastName;
|
||||
@Position(1)
|
||||
private String instrument;
|
||||
|
||||
public Beatle(String lastName, String instrument) {
|
||||
this.lastName = lastName;
|
||||
this.instrument = instrument;
|
||||
}
|
||||
|
||||
public String getInstrument() {
|
||||
return instrument;
|
||||
}
|
||||
|
||||
public void setInstrument(String instrument) {
|
||||
this.instrument = instrument;
|
||||
}
|
||||
|
||||
public String getLastName() {
|
||||
return lastName;
|
||||
}
|
||||
|
||||
public void setLastName(String lastName) {
|
||||
this.lastName = lastName;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
|
||||
<kbase name="backward_chaining" packages="backward_chaining">
|
||||
<ksession name="ksession-backward-chaining"/>
|
||||
</kbase>
|
||||
</kmodule>
|
|
@ -0,0 +1,44 @@
|
|||
package com.baeldung
|
||||
|
||||
import com.baeldung.model.Beatle;
|
||||
|
||||
|
||||
query whichBeatle(String lastName, String instrument)
|
||||
Beatle(lastName, instrument;)
|
||||
or
|
||||
(Beatle(lastName, null;)
|
||||
and
|
||||
whichBeatle(null, instrument;)) //recursive call to the function that allows to search in a derivation tree structure
|
||||
end
|
||||
|
||||
rule "Ringo"
|
||||
when
|
||||
String(this == "Ringo")
|
||||
whichBeatle("Starr", "drums";)
|
||||
then
|
||||
System.out.println("The beatle is Ringo Starr");
|
||||
end
|
||||
|
||||
rule "Paul"
|
||||
when
|
||||
String(this == "Paul")
|
||||
whichBeatle("McCartney", "bass";)
|
||||
then
|
||||
System.out.println("The beatle is Paul McCartney");
|
||||
end
|
||||
|
||||
rule "John"
|
||||
when
|
||||
String(this == "John")
|
||||
whichBeatle("Lennon", "guitar";)
|
||||
then
|
||||
System.out.println("The beatle is John Lennon");
|
||||
end
|
||||
|
||||
rule "George"
|
||||
when
|
||||
String(this == "George")
|
||||
whichBeatle("Harrison", "guitar";)
|
||||
then
|
||||
System.out.println("The beatle is George Harrison");
|
||||
end
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1,59 @@
|
|||
<?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>com.forketyfork.guest</groupId>
|
||||
<artifactId>spring-mvc</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>spring-mvc</name>
|
||||
<description>Spring MVC sample project</description>
|
||||
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.0.M5</version>
|
||||
<relativePath/> <!-- lookup parent from repository -->
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>spring-milestones</id>
|
||||
<name>Spring Milestones</name>
|
||||
<url>https://repo.spring.io/milestone</url>
|
||||
<snapshots>
|
||||
<enabled>false</enabled>
|
||||
</snapshots>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
||||
<java.version>1.8</java.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
|
@ -0,0 +1,15 @@
|
|||
package com.forketyfork.guest.springmvc;
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.context.annotation.ComponentScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
@ComponentScan(basePackages = {"com.forketyfork.guest.springmvc"})
|
||||
public class Spring5Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Spring5Application.class, args);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package com.forketyfork.guest.springmvc.model;
|
||||
|
||||
public class LoginData {
|
||||
|
||||
private String login;
|
||||
|
||||
private String password;
|
||||
|
||||
public LoginData() {
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
package com.forketyfork.guest.springmvc.web;
|
||||
|
||||
import com.forketyfork.guest.springmvc.model.LoginData;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.servlet.ModelAndView;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@Controller
|
||||
public class InternalsController {
|
||||
|
||||
private static final String LOGIN = "jack";
|
||||
private static final String PASSWORD = "halloween";
|
||||
|
||||
@GetMapping("/")
|
||||
public String hello() {
|
||||
return "login";
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public ModelAndView login(LoginData loginData) {
|
||||
if (LOGIN.equals(loginData.getLogin()) && PASSWORD.equals(loginData.getPassword())) {
|
||||
return new ModelAndView("success", Collections.singletonMap("login", loginData.getLogin()));
|
||||
} else {
|
||||
return new ModelAndView("failure", Collections.singletonMap("login", loginData.getLogin()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Login Failure</title>
|
||||
</head>
|
||||
<p>
|
||||
User with login <span th:text="${login}"></span> not found, please <a href="/">try again</a>.
|
||||
</p>
|
||||
</html>
|
|
@ -0,0 +1,13 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<head><title>Login Form</title></head>
|
||||
<body>
|
||||
|
||||
<form method="post" action="/login">
|
||||
<input type="text" placeholder="Login" name="login"/>
|
||||
<input type="password" placeholder="Password" name="password"/>
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
|
||||
</body>
|
||||
</html>
|
|
@ -0,0 +1,10 @@
|
|||
<!DOCTYPE html>
|
||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
||||
xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<title>Login Success</title>
|
||||
</head>
|
||||
<p>
|
||||
Hello, <span th:text="${login}"></span>!
|
||||
</p>
|
||||
</html>
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -2,7 +2,6 @@
|
|||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>hystrix</artifactId>
|
||||
<version>1.0</version>
|
||||
<name>hystrix</name>
|
||||
|
|
|
@ -10,53 +10,53 @@ import org.junit.Test;
|
|||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
|
||||
public class HystrixTimeoutIntegrationTest {
|
||||
public class HystrixTimeoutManualTest {
|
||||
|
||||
@Test
|
||||
public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob(){
|
||||
public void givenInputBobAndDefaultSettings_whenCommandExecuted_thenReturnHelloBob() {
|
||||
assertThat(new CommandHelloWorld("Bob").execute(), equalTo("Hello Bob!"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSvcTimeoutOf100AndDefaultSettings_whenRemoteSvcExecuted_thenReturnSuccess()
|
||||
throws InterruptedException {
|
||||
throws InterruptedException {
|
||||
HystrixCommand.Setter config = HystrixCommand
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2"));
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroup2"));
|
||||
|
||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(100)).execute(),
|
||||
equalTo("Success"));
|
||||
equalTo("Success"));
|
||||
}
|
||||
|
||||
@Test(expected = HystrixRuntimeException.class)
|
||||
public void givenSvcTimeoutOf10000AndDefaultSettings__whenRemoteSvcExecuted_thenExpectHRE() throws InterruptedException {
|
||||
HystrixCommand.Setter config = HystrixCommand
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3"));
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest3"));
|
||||
new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(10_000)).execute();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenSvcTimeoutOf5000AndExecTimeoutOf10000_whenRemoteSvcExecuted_thenReturnSuccess()
|
||||
throws InterruptedException {
|
||||
throws InterruptedException {
|
||||
|
||||
HystrixCommand.Setter config = HystrixCommand
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4"));
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest4"));
|
||||
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
|
||||
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
|
||||
config.andCommandPropertiesDefaults(commandProperties);
|
||||
|
||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
|
||||
equalTo("Success"));
|
||||
equalTo("Success"));
|
||||
}
|
||||
|
||||
@Test(expected = HystrixRuntimeException.class)
|
||||
public void givenSvcTimeoutOf15000AndExecTimeoutOf5000__whenExecuted_thenExpectHRE()
|
||||
throws InterruptedException {
|
||||
throws InterruptedException {
|
||||
HystrixCommand.Setter config = HystrixCommand
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5"));
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupTest5"));
|
||||
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
|
||||
commandProperties.withExecutionTimeoutInMilliseconds(5_000);
|
||||
config.andCommandPropertiesDefaults(commandProperties);
|
||||
|
@ -65,45 +65,45 @@ public class HystrixTimeoutIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void givenSvcTimeoutOf500AndExecTimeoutOf10000AndThreadPool__whenExecuted_thenReturnSuccess()
|
||||
throws InterruptedException {
|
||||
throws InterruptedException {
|
||||
|
||||
HystrixCommand.Setter config = HystrixCommand
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool"));
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupThreadPool"));
|
||||
HystrixCommandProperties.Setter commandProperties = HystrixCommandProperties.Setter();
|
||||
commandProperties.withExecutionTimeoutInMilliseconds(10_000);
|
||||
config.andCommandPropertiesDefaults(commandProperties);
|
||||
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
|
||||
.withMaxQueueSize(10)
|
||||
.withCoreSize(3)
|
||||
.withQueueSizeRejectionThreshold(10));
|
||||
.withMaxQueueSize(10)
|
||||
.withCoreSize(3)
|
||||
.withQueueSizeRejectionThreshold(10));
|
||||
|
||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
|
||||
equalTo("Success"));
|
||||
equalTo("Success"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenCircuitBreakerSetup__whenRemoteSvcCmdExecuted_thenReturnSuccess()
|
||||
throws InterruptedException {
|
||||
throws InterruptedException {
|
||||
|
||||
HystrixCommand.Setter config = HystrixCommand
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker"));
|
||||
.Setter
|
||||
.withGroupKey(HystrixCommandGroupKey.Factory.asKey("RemoteServiceGroupCircuitBreaker"));
|
||||
HystrixCommandProperties.Setter properties = HystrixCommandProperties.Setter();
|
||||
properties.withExecutionTimeoutInMilliseconds(1000);
|
||||
|
||||
properties.withCircuitBreakerSleepWindowInMilliseconds(4000);
|
||||
properties.withExecutionIsolationStrategy(
|
||||
HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
|
||||
HystrixCommandProperties.ExecutionIsolationStrategy.THREAD);
|
||||
properties.withCircuitBreakerEnabled(true);
|
||||
properties.withCircuitBreakerRequestVolumeThreshold(1);
|
||||
|
||||
config.andCommandPropertiesDefaults(properties);
|
||||
|
||||
config.andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
|
||||
.withMaxQueueSize(1)
|
||||
.withCoreSize(1)
|
||||
.withQueueSizeRejectionThreshold(1));
|
||||
.withMaxQueueSize(1)
|
||||
.withCoreSize(1)
|
||||
.withQueueSizeRejectionThreshold(1));
|
||||
|
||||
assertThat(this.invokeRemoteService(config, 10_000), equalTo(null));
|
||||
assertThat(this.invokeRemoteService(config, 10_000), equalTo(null));
|
||||
|
@ -111,19 +111,19 @@ public class HystrixTimeoutIntegrationTest {
|
|||
Thread.sleep(5000);
|
||||
|
||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
|
||||
equalTo("Success"));
|
||||
equalTo("Success"));
|
||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
|
||||
equalTo("Success"));
|
||||
equalTo("Success"));
|
||||
assertThat(new RemoteServiceTestCommand(config, new RemoteServiceTestSimulator(500)).execute(),
|
||||
equalTo("Success"));
|
||||
equalTo("Success"));
|
||||
}
|
||||
|
||||
public String invokeRemoteService(HystrixCommand.Setter config, int timeout)
|
||||
throws InterruptedException {
|
||||
throws InterruptedException {
|
||||
String response = null;
|
||||
try {
|
||||
response = new RemoteServiceTestCommand(config,
|
||||
new RemoteServiceTestSimulator(timeout)).execute();
|
||||
new RemoteServiceTestSimulator(timeout)).execute();
|
||||
} catch (HystrixRuntimeException ex) {
|
||||
System.out.println("ex = " + ex);
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -16,7 +16,7 @@
|
|||
<dep.ver.metrics>3.1.2</dep.ver.metrics>
|
||||
<dep.ver.servlet>3.1.0</dep.ver.servlet>
|
||||
<netflix.servo.ver>0.12.17</netflix.servo.ver>
|
||||
<micrometer.ver>1.0.0-rc.2</micrometer.ver>
|
||||
<micrometer.ver>0.12.0.RELEASE</micrometer.ver>
|
||||
<spring.boot.ver>2.0.0.M5</spring.boot.ver>
|
||||
</properties>
|
||||
|
||||
|
|
|
@ -16,6 +16,7 @@ import java.util.*;
|
|||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.micrometer.core.instrument.Meter.Type;
|
||||
import static org.hamcrest.CoreMatchers.*;
|
||||
import static org.hamcrest.collection.IsMapContaining.hasEntry;
|
||||
import static org.hamcrest.core.IsCollectionContaining.hasItems;
|
||||
|
@ -27,7 +28,7 @@ import static org.junit.Assert.assertTrue;
|
|||
*/
|
||||
public class MicrometerAtlasTest {
|
||||
|
||||
AtlasConfig atlasConfig;
|
||||
private AtlasConfig atlasConfig;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
|
@ -208,32 +209,27 @@ public class MicrometerAtlasTest {
|
|||
timer.record(8, TimeUnit.SECONDS);
|
||||
timer.record(13, TimeUnit.SECONDS);
|
||||
|
||||
List<Gauge> quantileGauges = registry
|
||||
Map<String, Integer> quantileMap = extractTagValueMap(registry, Type.Gauge, 1e9);
|
||||
assertThat(quantileMap, allOf(hasEntry("quantile=0.3", 2), hasEntry("quantile=0.5", 3), hasEntry("quantile=0.95", 8)));
|
||||
}
|
||||
|
||||
private Map<String, Integer> extractTagValueMap(MeterRegistry registry, Type meterType, double valueDivisor) {
|
||||
return registry
|
||||
.getMeters()
|
||||
.stream()
|
||||
.filter(meter -> meter
|
||||
.getType()
|
||||
.name()
|
||||
.equals("Gauge"))
|
||||
.map(meter -> (Gauge) meter)
|
||||
.collect(Collectors.toList());
|
||||
assert (3 == quantileGauges.size());
|
||||
|
||||
Map<String, Integer> quantileMap = quantileGauges
|
||||
.stream()
|
||||
.collect(Collectors.toMap(gauge -> {
|
||||
Tag tag = gauge
|
||||
.filter(meter -> meter.getType() == meterType)
|
||||
.collect(Collectors.toMap(meter -> {
|
||||
Tag tag = meter
|
||||
.getId()
|
||||
.getTags()
|
||||
.iterator()
|
||||
.next();
|
||||
return tag.getKey() + "=" + tag.getValue();
|
||||
}, gauge -> (int) (gauge.value() / 1e9)));
|
||||
|
||||
assertThat(quantileMap.keySet(), hasItems("quantile=0.3", "quantile=0.5", "quantile=0.95"));
|
||||
assertThat(quantileMap.get("quantile=0.3"), is(2));
|
||||
assertThat(quantileMap.get("quantile=0.5"), is(3));
|
||||
assertThat(quantileMap.get("quantile=0.95"), is(8));
|
||||
}, meter -> (int) (meter
|
||||
.measure()
|
||||
.iterator()
|
||||
.next()
|
||||
.getValue() / valueDivisor)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -243,6 +239,7 @@ public class MicrometerAtlasTest {
|
|||
.builder("summary")
|
||||
.histogram(Histogram.linear(0, 10, 5))
|
||||
.register(registry);
|
||||
|
||||
hist.record(3);
|
||||
hist.record(8);
|
||||
hist.record(20);
|
||||
|
@ -250,22 +247,7 @@ public class MicrometerAtlasTest {
|
|||
hist.record(13);
|
||||
hist.record(26);
|
||||
|
||||
Map<String, Integer> histograms = registry
|
||||
.getMeters()
|
||||
.stream()
|
||||
.filter(meter -> meter.getType() == Meter.Type.Counter)
|
||||
.collect(Collectors.toMap(counter -> {
|
||||
Tag tag = counter
|
||||
.getId()
|
||||
.getTags()
|
||||
.iterator()
|
||||
.next();
|
||||
return tag.getKey() + "=" + tag.getValue();
|
||||
}, counter -> (int) counter
|
||||
.measure()
|
||||
.iterator()
|
||||
.next()
|
||||
.getValue()));
|
||||
Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);
|
||||
|
||||
assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=10.0", 2), hasEntry("bucket=20.0", 2), hasEntry("bucket=30.0", 1), hasEntry("bucket=40.0", 1), hasEntry("bucket=Infinity", 0)));
|
||||
}
|
||||
|
@ -284,22 +266,7 @@ public class MicrometerAtlasTest {
|
|||
timer.record(341, TimeUnit.MILLISECONDS);
|
||||
timer.record(500, TimeUnit.MILLISECONDS);
|
||||
|
||||
Map<String, Integer> histograms = registry
|
||||
.getMeters()
|
||||
.stream()
|
||||
.filter(meter -> meter.getType() == Meter.Type.Counter)
|
||||
.collect(Collectors.toMap(counter -> {
|
||||
Tag tag = counter
|
||||
.getId()
|
||||
.getTags()
|
||||
.iterator()
|
||||
.next();
|
||||
return tag.getKey() + "=" + tag.getValue();
|
||||
}, counter -> (int) counter
|
||||
.measure()
|
||||
.iterator()
|
||||
.next()
|
||||
.getValue()));
|
||||
Map<String, Integer> histograms = extractTagValueMap(registry, Type.Counter, 1.0);
|
||||
|
||||
assertThat(histograms, allOf(hasEntry("bucket=0.0", 0), hasEntry("bucket=2.0E8", 1), hasEntry("bucket=4.0E8", 1), hasEntry("bucket=Infinity", 3)));
|
||||
|
||||
|
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
class LuckyNumberGenerator {
|
||||
|
||||
public int getLuckyNumber(String name) {
|
||||
|
||||
saveIntoDatabase(name);
|
||||
|
||||
if (name == null) {
|
||||
return getDefaultLuckyNumber();
|
||||
}
|
||||
|
||||
return getComputedLuckyNumber(name.length());
|
||||
}
|
||||
|
||||
private void saveIntoDatabase(String name) {
|
||||
// Save the name into the database
|
||||
}
|
||||
|
||||
private int getDefaultLuckyNumber() {
|
||||
return 100;
|
||||
}
|
||||
|
||||
private int getComputedLuckyNumber(int length) {
|
||||
return length < 5 ? 5 : 10000;
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,51 @@
|
|||
package com.baeldung.powermockito.introduction;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.powermock.api.mockito.PowerMockito.doReturn;
|
||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
||||
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
|
||||
import static org.powermock.api.mockito.PowerMockito.when;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
||||
import org.powermock.modules.junit4.PowerMockRunner;
|
||||
|
||||
@RunWith(PowerMockRunner.class)
|
||||
@PrepareForTest(fullyQualifiedNames = "com.baeldung.powermockito.introduction.LuckyNumberGenerator")
|
||||
public class LuckyNumberGeneratorTest {
|
||||
|
||||
@Test
|
||||
public final void givenPrivateMethodWithReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
|
||||
|
||||
when(mock, "getDefaultLuckyNumber").thenReturn(300);
|
||||
|
||||
int result = mock.getLuckyNumber(null);
|
||||
|
||||
assertEquals(300, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenPrivateMethodWithArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
|
||||
|
||||
doReturn(1).when(mock, "getComputedLuckyNumber", ArgumentMatchers.anyInt());
|
||||
|
||||
int result = mock.getLuckyNumber("Jack");
|
||||
|
||||
assertEquals(1, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void givenPrivateMethodWithNoArgumentAndReturn_whenUsingPowerMockito_thenCorrect() throws Exception {
|
||||
LuckyNumberGenerator mock = spy(new LuckyNumberGenerator());
|
||||
|
||||
int result = mock.getLuckyNumber("Tyranosorous");
|
||||
|
||||
verifyPrivate(mock).invoke("saveIntoDatabase", ArgumentMatchers.anyString());
|
||||
assertEquals(10000, result);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -1,55 +1,53 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static io.restassured.RestAssured.get;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
public class RestAssured2IntegrationTest {
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
private static final int PORT = 8084;
|
||||
private static WireMockServer wireMockServer = new WireMockServer(PORT);
|
||||
|
||||
private static final String EVENTS_PATH = "/odds";
|
||||
private static final String APPLICATION_JSON = "application/json";
|
||||
private static final String ODDS = getJson();
|
||||
private static final String EVENTS_PATH = "/odds";
|
||||
private static final String APPLICATION_JSON = "application/json";
|
||||
private static final String ODDS = getJson();
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(ODDS)));
|
||||
}
|
||||
@BeforeClass
|
||||
public static void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", PORT);
|
||||
RestAssured.port = PORT;
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(ODDS)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
|
||||
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
|
||||
hasItems(5.25f, 1.2f));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
|
||||
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
|
||||
hasItems(5.25f, 1.2f));
|
||||
}
|
||||
|
||||
private static String getJson() {
|
||||
|
||||
return Util.inputStreamToString(new RestAssured2IntegrationTest().getClass()
|
||||
.getResourceAsStream("/odds.json"));
|
||||
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
private static String getJson() {
|
||||
return Util.inputStreamToString(RestAssured2IntegrationTest.class
|
||||
.getResourceAsStream("/odds.json"));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,14 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import com.github.fge.jsonschema.SchemaVersion;
|
||||
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
|
||||
import com.github.fge.jsonschema.main.JsonSchemaFactory;
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
|
@ -11,96 +20,86 @@ import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
|
|||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.github.fge.jsonschema.SchemaVersion;
|
||||
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
|
||||
import com.github.fge.jsonschema.main.JsonSchemaFactory;
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
public class RestAssuredIntegrationTest {
|
||||
private static final int PORT = 8083;
|
||||
private static WireMockServer wireMockServer = new WireMockServer(PORT);
|
||||
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
private static final String EVENTS_PATH = "/events?id=390";
|
||||
private static final String APPLICATION_JSON = "application/json";
|
||||
private static final String GAME_ODDS = getEventJson();
|
||||
private static final String EVENTS_PATH = "/events?id=390";
|
||||
private static final String APPLICATION_JSON = "application/json";
|
||||
private static final String GAME_ODDS = getEventJson();
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(GAME_ODDS)));
|
||||
}
|
||||
@BeforeClass
|
||||
public static void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
RestAssured.port = PORT;
|
||||
configureFor("localhost", PORT);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_JSON)
|
||||
.withBody(GAME_ODDS)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body("odd.ck", equalTo(12.2f));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body("odd.ck", equalTo(12.2f));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
|
||||
@Test
|
||||
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
|
||||
|
||||
get("/events?id=390").then().statusCode(200).assertThat()
|
||||
.body("id", equalTo("390"));
|
||||
get("/events?id=390").then().statusCode(200).assertThat()
|
||||
.body("id", equalTo("390"));
|
||||
}
|
||||
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json"));
|
||||
}
|
||||
|
||||
get("/events?id=390").then().assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json"));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
|
||||
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
|
||||
.newBuilder()
|
||||
.setValidationConfiguration(
|
||||
ValidationConfiguration.newBuilder()
|
||||
.setDefaultVersion(SchemaVersion.DRAFTV4)
|
||||
.freeze()).freeze();
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
|
||||
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
|
||||
.newBuilder()
|
||||
.setValidationConfiguration(
|
||||
ValidationConfiguration.newBuilder()
|
||||
.setDefaultVersion(SchemaVersion.DRAFTV4)
|
||||
.freeze()).freeze();
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
jsonSchemaFactory));
|
||||
}
|
||||
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
jsonSchemaFactory));
|
||||
@Test
|
||||
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
|
||||
|
||||
}
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
settings().with().checkedValidation(false)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
|
||||
|
||||
get("/events?id=390")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(matchesJsonSchemaInClasspath("event_0.json").using(
|
||||
settings().with().checkedValidation(false)));
|
||||
}
|
||||
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
private static String getEventJson() {
|
||||
return Util.inputStreamToString(RestAssuredIntegrationTest.class
|
||||
.getResourceAsStream("/event_0.json"));
|
||||
}
|
||||
@AfterClass
|
||||
public static void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
private static String getEventJson() {
|
||||
return Util.inputStreamToString(RestAssuredIntegrationTest.class
|
||||
.getResourceAsStream("/event_0.json"));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,54 +1,55 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import static io.restassured.RestAssured.get;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
public class RestAssuredXML2IntegrationTest {
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
private static final int PORT = 8082;
|
||||
private static WireMockServer wireMockServer = new WireMockServer(PORT);
|
||||
|
||||
private static final String EVENTS_PATH = "/teachers";
|
||||
private static final String APPLICATION_XML = "application/xml";
|
||||
private static final String TEACHERS = getXml();
|
||||
private static final String EVENTS_PATH = "/teachers";
|
||||
private static final String APPLICATION_XML = "application/xml";
|
||||
private static final String TEACHERS = getXml();
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_XML)
|
||||
.withBody(TEACHERS)));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
|
||||
get("/teachers")
|
||||
.then()
|
||||
.body("teachers.teacher.find { it.@department == 'science' }.subject",
|
||||
hasItems("math", "physics"));
|
||||
}
|
||||
private static String getXml() {
|
||||
|
||||
return Util
|
||||
.inputStreamToString(new RestAssuredXML2IntegrationTest().getClass().getResourceAsStream("/teachers.xml"));
|
||||
|
||||
}
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
@BeforeClass
|
||||
public static void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
RestAssured.port = PORT;
|
||||
configureFor("localhost", PORT);
|
||||
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_XML)
|
||||
.withBody(TEACHERS)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
|
||||
get("/teachers")
|
||||
.then()
|
||||
.body("teachers.teacher.find { it.@department == 'science' }.subject",
|
||||
hasItems("math", "physics"));
|
||||
}
|
||||
|
||||
private static String getXml() {
|
||||
return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class
|
||||
.getResourceAsStream("/teachers.xml"));
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,99 +1,90 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
import io.restassured.RestAssured;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.get;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.post;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
|
||||
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
|
||||
import static io.restassured.RestAssured.post;
|
||||
import static io.restassured.RestAssured.get;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
|
||||
import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.hasItems;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.xml.HasXPath.hasXPath;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.github.fge.jsonschema.SchemaVersion;
|
||||
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
|
||||
import com.github.fge.jsonschema.main.JsonSchemaFactory;
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
public class RestAssuredXMLIntegrationTest {
|
||||
private WireMockServer wireMockServer = new WireMockServer();
|
||||
private static final String EVENTS_PATH = "/employees";
|
||||
private static final String APPLICATION_XML = "application/xml";
|
||||
private static final String EMPLOYEES = getXml();
|
||||
private static final int PORT = 8081;
|
||||
private static WireMockServer wireMockServer = new WireMockServer(PORT);
|
||||
|
||||
@Before
|
||||
public void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", 8080);
|
||||
stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_XML)
|
||||
.withBody(EMPLOYEES)));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"));
|
||||
}
|
||||
private static final String EVENTS_PATH = "/employees";
|
||||
private static final String APPLICATION_XML = "application/xml";
|
||||
private static final String EMPLOYEES = getXml();
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"))
|
||||
.body("employees.employee.last-name", equalTo("Daisy"))
|
||||
.body("employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
@BeforeClass
|
||||
public static void before() throws Exception {
|
||||
System.out.println("Setting up!");
|
||||
wireMockServer.start();
|
||||
configureFor("localhost", PORT);
|
||||
RestAssured.port = PORT;
|
||||
stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
|
||||
aResponse().withStatus(200)
|
||||
.withHeader("Content-Type", APPLICATION_XML)
|
||||
.withBody(EMPLOYEES)));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"),
|
||||
"employees.employee.last-name", equalTo("Daisy"),
|
||||
"employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name",
|
||||
containsString("Ja")));
|
||||
@Test
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
|
||||
post("/employees").then().assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"))
|
||||
.body("employees.employee.last-name", equalTo("Daisy"))
|
||||
.body("employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body("employees.employee.first-name", equalTo("Jane"),
|
||||
"employees.employee.last-name", equalTo("Daisy"),
|
||||
"employees.employee.sex", equalTo("f"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
|
||||
@Test
|
||||
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name",
|
||||
containsString("Ja")));
|
||||
}
|
||||
|
||||
}
|
||||
@Test
|
||||
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
|
||||
post("/employees")
|
||||
.then()
|
||||
.assertThat()
|
||||
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
|
||||
}
|
||||
|
||||
private static String getXml() {
|
||||
return Util
|
||||
.inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml"));
|
||||
}
|
||||
|
||||
private static String getXml() {
|
||||
|
||||
return Util
|
||||
.inputStreamToString(new RestAssuredXMLIntegrationTest().getClass().getResourceAsStream("/employees.xml"));
|
||||
|
||||
}
|
||||
@After
|
||||
public void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
@AfterClass
|
||||
public static void after() throws Exception {
|
||||
System.out.println("Running: tearDown");
|
||||
wireMockServer.stop();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,36 +1,15 @@
|
|||
package com.baeldung.restassured;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Util {
|
||||
public static String inputStreamToString(InputStream is) {
|
||||
BufferedReader br = null;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
final class Util {
|
||||
|
||||
String line;
|
||||
try {
|
||||
private Util() {
|
||||
}
|
||||
|
||||
br = new BufferedReader(new InputStreamReader(is));
|
||||
while ((line = br.readLine()) != null) {
|
||||
sb.append(line);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (br != null) {
|
||||
try {
|
||||
br.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
|
||||
}
|
||||
static String inputStreamToString(InputStream is) {
|
||||
Scanner s = new Scanner(is).useDelimiter("\\A");
|
||||
return s.hasNext() ? s.next() : "";
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -1,22 +1,21 @@
|
|||
package com.baeldung;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
@RestController
|
||||
public class BaeldungController {
|
||||
|
||||
@RequestMapping(method = { RequestMethod.GET }, value = { "/hello" })
|
||||
@GetMapping("/hello")
|
||||
public String sayHello(HttpServletResponse response) {
|
||||
return "hello";
|
||||
}
|
||||
|
||||
@RequestMapping(method = { RequestMethod.POST }, value = { "/baeldung" })
|
||||
@PostMapping("/baeldung")
|
||||
public String sayHelloPost(HttpServletResponse response) {
|
||||
return "hello";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -2,23 +2,16 @@ package com.baeldung;
|
|||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.boot.context.web.SpringBootServletInitializer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@SpringBootApplication
|
||||
public class SpringDemoApplication extends SpringBootServletInitializer {
|
||||
public class SpringDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SpringDemoApplication.class, args);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
||||
return application.sources(SpringDemoApplication.class);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestTemplate getRestTemplate() {
|
||||
return new RestTemplate();
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
server.port=8082
|
|
@ -1,16 +0,0 @@
|
|||
package com.baeldung;
|
||||
|
||||
import cucumber.api.java.en.Given;
|
||||
import cucumber.api.java.en.When;
|
||||
|
||||
public class OtherDefsIntegrationTest extends SpringIntegrationTest {
|
||||
@When("^the client calls /baeldung$")
|
||||
public void the_client_issues_POST_hello() throws Throwable {
|
||||
executePost("http://localhost:8080/baeldung");
|
||||
}
|
||||
|
||||
@Given("^the client calls /hello$")
|
||||
public void the_client_issues_GET_hello() throws Throwable {
|
||||
executeGet("http://localhost:8080/hello");
|
||||
}
|
||||
}
|
|
@ -11,23 +11,19 @@ public class ResponseResults {
|
|||
private final ClientHttpResponse theResponse;
|
||||
private final String body;
|
||||
|
||||
protected ResponseResults(final ClientHttpResponse response) throws IOException {
|
||||
ResponseResults(final ClientHttpResponse response) throws IOException {
|
||||
this.theResponse = response;
|
||||
final InputStream bodyInputStream = response.getBody();
|
||||
if (null == bodyInputStream) {
|
||||
this.body = "{}";
|
||||
} else {
|
||||
final StringWriter stringWriter = new StringWriter();
|
||||
IOUtils.copy(bodyInputStream, stringWriter);
|
||||
this.body = stringWriter.toString();
|
||||
}
|
||||
final StringWriter stringWriter = new StringWriter();
|
||||
IOUtils.copy(bodyInputStream, stringWriter);
|
||||
this.body = stringWriter.toString();
|
||||
}
|
||||
|
||||
protected ClientHttpResponse getTheResponse() {
|
||||
ClientHttpResponse getTheResponse() {
|
||||
return theResponse;
|
||||
}
|
||||
|
||||
protected String getBody() {
|
||||
String getBody() {
|
||||
return body;
|
||||
}
|
||||
}
|
|
@ -1,9 +1,5 @@
|
|||
package com.baeldung;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.IntegrationTest;
|
||||
import org.springframework.boot.test.SpringApplicationContextLoader;
|
||||
|
@ -12,40 +8,39 @@ import org.springframework.http.client.ClientHttpResponse;
|
|||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.web.WebAppConfiguration;
|
||||
import org.springframework.web.client.ResponseErrorHandler;
|
||||
import org.springframework.web.client.ResponseExtractor;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
//@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@ContextConfiguration(classes = SpringDemoApplication.class, loader = SpringApplicationContextLoader.class)
|
||||
@WebAppConfiguration
|
||||
@IntegrationTest
|
||||
public class SpringIntegrationTest {
|
||||
protected static ResponseResults latestResponse = null;
|
||||
static ResponseResults latestResponse = null;
|
||||
|
||||
@Autowired
|
||||
protected RestTemplate restTemplate;
|
||||
|
||||
protected void executeGet(String url) throws IOException {
|
||||
void executeGet(String url) throws IOException {
|
||||
final Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Accept", "application/json");
|
||||
final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers);
|
||||
final ResponseResultErrorHandler errorHandler = new ResponseResultErrorHandler();
|
||||
|
||||
restTemplate.setErrorHandler(errorHandler);
|
||||
latestResponse = restTemplate.execute(url, HttpMethod.GET, requestCallback, new ResponseExtractor<ResponseResults>() {
|
||||
@Override
|
||||
public ResponseResults extractData(ClientHttpResponse response) throws IOException {
|
||||
if (errorHandler.hadError) {
|
||||
return (errorHandler.getResults());
|
||||
} else {
|
||||
return (new ResponseResults(response));
|
||||
}
|
||||
latestResponse = restTemplate.execute(url, HttpMethod.GET, requestCallback, response -> {
|
||||
if (errorHandler.hadError) {
|
||||
return (errorHandler.getResults());
|
||||
} else {
|
||||
return (new ResponseResults(response));
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
protected void executePost(String url) throws IOException {
|
||||
void executePost() throws IOException {
|
||||
final Map<String, String> headers = new HashMap<>();
|
||||
headers.put("Accept", "application/json");
|
||||
final HeaderSettingRequestCallback requestCallback = new HeaderSettingRequestCallback(headers);
|
||||
|
@ -56,17 +51,14 @@ public class SpringIntegrationTest {
|
|||
}
|
||||
|
||||
restTemplate.setErrorHandler(errorHandler);
|
||||
latestResponse = restTemplate.execute(url, HttpMethod.POST, requestCallback, new ResponseExtractor<ResponseResults>() {
|
||||
@Override
|
||||
public ResponseResults extractData(ClientHttpResponse response) throws IOException {
|
||||
if (errorHandler.hadError) {
|
||||
return (errorHandler.getResults());
|
||||
} else {
|
||||
return (new ResponseResults(response));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
latestResponse = restTemplate
|
||||
.execute("http://localhost:8082/baeldung", HttpMethod.POST, requestCallback, response -> {
|
||||
if (errorHandler.hadError) {
|
||||
return (errorHandler.getResults());
|
||||
} else {
|
||||
return (new ResponseResults(response));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private class ResponseResultErrorHandler implements ResponseErrorHandler {
|
||||
|
|
|
@ -3,6 +3,7 @@ package com.baeldung;
|
|||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.is;
|
||||
|
||||
import cucumber.api.java.en.Given;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import cucumber.api.java.en.And;
|
||||
|
@ -11,9 +12,19 @@ import cucumber.api.java.en.When;
|
|||
|
||||
public class StepDefsIntegrationTest extends SpringIntegrationTest {
|
||||
|
||||
@When("^the client calls /baeldung$")
|
||||
public void the_client_issues_POST_hello() throws Throwable {
|
||||
executePost();
|
||||
}
|
||||
|
||||
@Given("^the client calls /hello$")
|
||||
public void the_client_issues_GET_hello() throws Throwable {
|
||||
executeGet("http://localhost:8082/hello");
|
||||
}
|
||||
|
||||
@When("^the client calls /version$")
|
||||
public void the_client_issues_GET_version() throws Throwable {
|
||||
executeGet("http://localhost:8080/version");
|
||||
executeGet("http://localhost:8082/version");
|
||||
}
|
||||
|
||||
@Then("^the client receives status code of (\\d+)$")
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -23,11 +23,8 @@ public class HibernateImmutableIntegrationTest {
|
|||
|
||||
@Before
|
||||
public void before() {
|
||||
session = HibernateUtil.getSessionFactory().getCurrentSession();
|
||||
session = HibernateUtil.getSessionFactory().openSession();
|
||||
session.beginTransaction();
|
||||
createEvent();
|
||||
createEventGenerated();
|
||||
session.setCacheMode(CacheMode.REFRESH);
|
||||
}
|
||||
|
||||
@BeforeClass
|
||||
|
@ -40,8 +37,6 @@ public class HibernateImmutableIntegrationTest {
|
|||
HibernateUtil.getSessionFactory().close();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void addEvent() {
|
||||
Event event = new Event();
|
||||
|
@ -49,15 +44,18 @@ public class HibernateImmutableIntegrationTest {
|
|||
event.setTitle("Public Event");
|
||||
session.save(event);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void updateEvent() {
|
||||
createEvent();
|
||||
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
|
||||
event.setTitle("Private Event");
|
||||
session.update(event);
|
||||
session.flush();
|
||||
session.refresh(event);
|
||||
session.close();
|
||||
|
||||
assertThat(event.getTitle(), equalTo("New Event"));
|
||||
assertThat(event.getId(), equalTo(5L));
|
||||
|
@ -65,13 +63,16 @@ public class HibernateImmutableIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void deleteEvent() {
|
||||
createEvent();
|
||||
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
|
||||
session.delete(event);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void addGuest() {
|
||||
createEvent();
|
||||
Event event = (Event) session.createQuery("FROM Event WHERE title='New Event'").list().get(0);
|
||||
String newGuest = "Sara";
|
||||
event.getGuestList().add(newGuest);
|
||||
|
@ -79,6 +80,7 @@ public class HibernateImmutableIntegrationTest {
|
|||
exception.expect(PersistenceException.class);
|
||||
session.save(event);
|
||||
session.getTransaction().commit();
|
||||
session.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -94,18 +96,18 @@ public class HibernateImmutableIntegrationTest {
|
|||
|
||||
@Test
|
||||
public void updateEventGenerated() {
|
||||
createEventGenerated();
|
||||
EventGeneratedId eventGeneratedId = (EventGeneratedId) session.createQuery("FROM EventGeneratedId WHERE name LIKE '%John%'").list().get(0);
|
||||
eventGeneratedId.setName("Mike");
|
||||
session.update(eventGeneratedId);
|
||||
session.flush();
|
||||
session.refresh(eventGeneratedId);
|
||||
session.close();
|
||||
|
||||
assertThat(eventGeneratedId.getName(), equalTo("John"));
|
||||
assertThat(eventGeneratedId.getId(), equalTo(1L));
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
private static void createEvent() {
|
||||
Event event = new Event(5L, "New Event", Sets.newHashSet("guest"));
|
||||
session.save(event);
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
|
@ -0,0 +1 @@
|
|||
## Relevant articles:
|
Loading…
Reference in New Issue