Merge branch 'master' into BAEL-4783-cucumber-tags-junit5
This commit is contained in:
@@ -1,3 +0,0 @@
|
||||
## Testing Modules
|
||||
|
||||
This is an aggregator module containing multiple modules focused on testing libraries.
|
||||
@@ -5,3 +5,4 @@
|
||||
- [Introduction to JUnitParams](http://www.baeldung.com/junit-params)
|
||||
- [Running JUnit Tests Programmatically, from a Java Application](https://www.baeldung.com/junit-tests-run-programmatically-from-java)
|
||||
- [Introduction to Lambda Behave](https://www.baeldung.com/lambda-behave)
|
||||
- [Conditionally Run or Ignore Tests in JUnit 4](https://www.baeldung.com/junit-conditional-assume)
|
||||
|
||||
+41
-19
@@ -5,37 +5,59 @@ import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assume.assumeFalse;
|
||||
import static org.junit.Assume.assumeThat;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
import static org.junit.Assume.assumeNotNull;
|
||||
import static org.junit.Assume.assumeNoException;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class ConditionallyIgnoreTestsUnitTest {
|
||||
|
||||
|
||||
@Test
|
||||
public void whenAssumeThatCodeVersionIsNot2_thenIgnore() {
|
||||
final int codeVersion = 1;
|
||||
assumeThat(codeVersion, is(2));
|
||||
|
||||
assertEquals("hello", "HELLO".toLowerCase());
|
||||
public void whenAssumeThatAndOSIsLinux_thenRunTest() {
|
||||
assumeThat(getOsName(), is("Linux"));
|
||||
assertEquals("run", "RUN".toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAssumeTrueOnCondition_thenIgnore() {
|
||||
final int codeVersion = 1;
|
||||
assumeTrue(isCodeVersion2(codeVersion));
|
||||
|
||||
assertEquals("hello", "HELLO".toLowerCase());
|
||||
public void whenAssumeTrueAndOSIsLinux_thenRunTest() {
|
||||
assumeTrue(isExpectedOS(getOsName()));
|
||||
assertEquals("run", "RUN".toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAssumeFalseOnCondition_thenIgnore() {
|
||||
final int codeVersion = 2;
|
||||
assumeFalse(isCodeVersion2(codeVersion));
|
||||
|
||||
assertEquals("hello", "HELLO".toLowerCase());
|
||||
public void whenAssumeFalseAndOSIsLinux_thenIgnore() {
|
||||
assumeFalse(isExpectedOS(getOsName()));
|
||||
assertEquals("run", "RUN".toLowerCase());
|
||||
}
|
||||
|
||||
private boolean isCodeVersion2(final int codeVersion) {
|
||||
return codeVersion == 2;
|
||||
@Test
|
||||
public void whenAssumeNotNullAndNotNullOSVersion_thenRun() {
|
||||
assumeNotNull(getOsName());
|
||||
assertEquals("run", "RUN".toLowerCase());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Let's use a different example here.
|
||||
*/
|
||||
@Test
|
||||
public void whenAssumeNoExceptionAndExceptionThrown_thenIgnore() {
|
||||
assertEquals("everything ok", "EVERYTHING OK".toLowerCase());
|
||||
String t = null;
|
||||
try {
|
||||
t.charAt(0);
|
||||
} catch (NullPointerException npe) {
|
||||
assumeNoException(npe);
|
||||
}
|
||||
assertEquals("run", "RUN".toLowerCase());
|
||||
}
|
||||
|
||||
private boolean isExpectedOS(final String osName) {
|
||||
return "Linux".equals(osName);
|
||||
}
|
||||
|
||||
// This should use System.getProperty("os.name") in a real test.
|
||||
private String getOsName() {
|
||||
return "Linux";
|
||||
}
|
||||
}
|
||||
@@ -35,18 +35,8 @@
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit-jupiter.version>5.4.2</junit-jupiter.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<junit.vintage.version>5.4.2</junit.vintage.version>
|
||||
</properties>
|
||||
|
||||
|
||||
+1
-1
@@ -46,7 +46,7 @@ public class TestResultLoggerExtension implements TestWatcher, AfterAllCallback
|
||||
|
||||
@Override
|
||||
public void testFailed(ExtensionContext context, Throwable cause) {
|
||||
LOG.info("Test Aborted for test {}: ", context.getDisplayName());
|
||||
LOG.info("Test Failed for test {}: ", context.getDisplayName());
|
||||
|
||||
testResultsStatus.add(TestResultStatus.FAILED);
|
||||
}
|
||||
|
||||
@@ -152,7 +152,6 @@
|
||||
<junit-platform.version>1.2.0</junit-platform.version>
|
||||
<junit-jupiter.version>5.4.2</junit-jupiter.version>
|
||||
<spring.version>5.0.6.RELEASE</spring.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+2
-2
@@ -28,8 +28,8 @@ public class BeforeAndAfterAnnotationsUnitTest {
|
||||
}
|
||||
|
||||
@After
|
||||
public void finalize() {
|
||||
LOG.info("finalize");
|
||||
public void teardown() {
|
||||
LOG.info("teardown");
|
||||
list.clear();
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -28,8 +28,8 @@ public class BeforeEachAndAfterEachAnnotationsUnitTest {
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
public void finalize() {
|
||||
LOG.info("finalize");
|
||||
public void teardown() {
|
||||
LOG.info("teardown");
|
||||
list.clear();
|
||||
}
|
||||
|
||||
|
||||
@@ -7,3 +7,4 @@
|
||||
- [Testing an Abstract Class With JUnit](https://www.baeldung.com/junit-test-abstract-class)
|
||||
- [Guide to Dynamic Tests in JUnit 5](https://www.baeldung.com/junit5-dynamic-tests)
|
||||
- [Determine the Execution Time of JUnit Tests](https://www.baeldung.com/junit-test-execution-time)
|
||||
- [@BeforeAll and @AfterAll in Non-Static Methods](https://www.baeldung.com/java-beforeall-afterall-non-static)
|
||||
|
||||
@@ -105,10 +105,6 @@
|
||||
</resource>
|
||||
</resources>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
@@ -140,7 +136,6 @@
|
||||
<log4j2.version>2.8.2</log4j2.version>
|
||||
<powermock.version>2.0.0</powermock.version>
|
||||
<maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
<spring.version>5.0.1.RELEASE</spring.version>
|
||||
<surefire.report.plugin>3.0.0-M3</surefire.report.plugin>
|
||||
</properties>
|
||||
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.junit5.nonstatic;
|
||||
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
|
||||
public class BeforeAndAfterAnnotationsUnitTest {
|
||||
|
||||
String input;
|
||||
Long result;
|
||||
|
||||
@BeforeAll
|
||||
public void setup() {
|
||||
input = "77";
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
public void teardown() {
|
||||
input = null;
|
||||
result = null;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenConvertStringToLong_thenResultShouldBeLong() {
|
||||
result = Long.valueOf(input);
|
||||
Assertions.assertEquals(77l, result);
|
||||
}
|
||||
}
|
||||
@@ -55,8 +55,8 @@
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<junit.jupiter.version>5.6.2</junit.jupiter.version>
|
||||
<junit.platform.version>1.6.0</junit.platform.version>
|
||||
<junit.jupiter.version>5.7.0</junit.jupiter.version>
|
||||
<junit.platform.version>1.7.0</junit.platform.version>
|
||||
<log4j2.version>2.8.2</log4j2.version>
|
||||
<assertj-core.version>3.11.1</assertj-core.version>
|
||||
</properties>
|
||||
|
||||
@@ -18,12 +18,12 @@
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-engine</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit.platform.version}</version>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
@@ -47,42 +47,13 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<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>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>java</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.TestLauncher</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<junit.jupiter.version>5.2.0</junit.jupiter.version>
|
||||
<junit.platform.version>1.2.0</junit.platform.version>
|
||||
<junit-platform.version>1.2.0</junit-platform.version>
|
||||
<junit.vintage.version>5.2.0</junit.vintage.version>
|
||||
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
|
||||
<exec-maven-plugin.version>1.6.0</exec-maven-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -37,7 +37,6 @@
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
@@ -55,11 +54,6 @@
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
@@ -77,7 +71,6 @@
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<version>2.0.5.RELEASE</version>
|
||||
</plugin>
|
||||
<!--<plugin>-->
|
||||
<!--<groupId>net.alchim31.maven</groupId>-->
|
||||
@@ -122,10 +115,10 @@
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<encoding>UTF-8</encoding>
|
||||
<scala.version>2.11.12</scala.version> <!--2.11.12 --> <!--2.12.6 -->
|
||||
<gatling.version>2.2.5</gatling.version> <!--2.2.5 --> <!--2.3.1 -->
|
||||
<scala-maven-plugin.version>3.2.2</scala-maven-plugin.version> <!--3.2.2 --> <!--3.3.2 -->
|
||||
<gatling-maven-plugin.version>2.2.1</gatling-maven-plugin.version> <!--2.2.1 --> <!--2.2.4 -->
|
||||
<scala.version>2.12.12</scala.version> <!--2.11.12 --> <!--2.12.6 -->
|
||||
<gatling.version>3.4.0</gatling.version> <!--2.2.5 --> <!--2.3.1 -->
|
||||
<scala-maven-plugin.version>4.4.0</scala-maven-plugin.version> <!--3.2.2 --> <!--3.3.2 -->
|
||||
<gatling-maven-plugin.version>3.1.0</gatling-maven-plugin.version> <!--2.2.1 --> <!--2.2.4 -->
|
||||
<jmeter.version>5.0</jmeter.version>
|
||||
</properties>
|
||||
|
||||
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
package com.baeldung.loadtesting;
|
||||
|
||||
import com.baeldung.loadtesting.model.Transaction;
|
||||
import com.baeldung.loadtesting.repository.TransactionRepository;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@Deprecated
|
||||
public class TransactionController {
|
||||
|
||||
@Autowired
|
||||
private TransactionRepository transactionRepository;
|
||||
|
||||
@PostMapping(path="/addTransaction")
|
||||
public @ResponseBody
|
||||
String saveTransactions(@RequestBody Transaction trnsctn){
|
||||
transactionRepository.save(trnsctn);
|
||||
return "Saved Transaction.";
|
||||
}
|
||||
|
||||
@GetMapping(path="/findAll/{rewardId}")
|
||||
public @ResponseBody Iterable<Transaction> getTransactions(@RequestParam Integer id){
|
||||
return transactionRepository.findByCustomerRewardsId(id);
|
||||
}
|
||||
}
|
||||
+17
-3
@@ -4,11 +4,11 @@ import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
|
||||
import lombok.Data;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Data
|
||||
@Table(indexes = {@Index(columnList="customerId")})
|
||||
public class CustomerRewardsAccount {
|
||||
|
||||
@Id
|
||||
@@ -19,4 +19,18 @@ public class CustomerRewardsAccount {
|
||||
public Integer getCustomerId(){
|
||||
return this.customerId;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setCustomerId(Integer customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
+34
-3
@@ -1,16 +1,17 @@
|
||||
package com.baeldung.loadtesting.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.GenerationType;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Index;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Calendar;
|
||||
|
||||
@Entity
|
||||
@Data
|
||||
@Table(indexes = {@Index(columnList="customerRewardsId")})
|
||||
public class Transaction {
|
||||
|
||||
@Id
|
||||
@@ -27,4 +28,34 @@ public class Transaction {
|
||||
public void setTransactionDate(Date transactionDate){
|
||||
this.transactionDate = transactionDate;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Integer getCustomerRewardsId() {
|
||||
return customerRewardsId;
|
||||
}
|
||||
|
||||
public void setCustomerRewardsId(Integer customerRewardsId) {
|
||||
this.customerRewardsId = customerRewardsId;
|
||||
}
|
||||
|
||||
public Integer getCustomerId() {
|
||||
return customerId;
|
||||
}
|
||||
|
||||
public void setCustomerId(Integer customerId) {
|
||||
this.customerId = customerId;
|
||||
}
|
||||
|
||||
public Date getTransactionDate() {
|
||||
return transactionDate;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
spring.h2.console.enabled=true
|
||||
spring.datasource.url=jdbc:h2:mem:testdb
|
||||
spring.datasource.driverClassName=org.h2.Driver
|
||||
spring.datasource.username=sa
|
||||
spring.datasource.password=
|
||||
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
|
||||
|
||||
+12
-17
@@ -7,46 +7,41 @@ import scala.concurrent.duration._
|
||||
|
||||
class RewardsScenario extends Simulation {
|
||||
|
||||
def randCustId() = Random.nextInt(99)
|
||||
def randCustId() = java.util.concurrent.ThreadLocalRandom.current().nextInt()
|
||||
|
||||
val httpProtocol = http.baseUrl("http://localhost:8080")
|
||||
.acceptHeader("text/html,application/json;q=0.9,*/*;q=0.8")
|
||||
.doNotTrackHeader("1")
|
||||
.acceptLanguageHeader("en-US,en;q=0.5")
|
||||
.acceptEncodingHeader("gzip, deflate")
|
||||
.userAgentHeader("Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0")
|
||||
|
||||
val scn = scenario("RewardsScenario")
|
||||
.repeat(10){
|
||||
.repeat(1000){
|
||||
|
||||
exec(http("transactions_add")
|
||||
.post("/transactions/add/")
|
||||
.body(StringBody("""{ "customerRewardsId":null,"customerId":""""+ randCustId() + """","transactionDate":null }""")).asJson
|
||||
.body(StringBody(_ => s"""{"customerRewardsId":null,"customerId":${randCustId()},"transactionDate":null}""")).asJson
|
||||
.check(jsonPath("$.id").saveAs("txnId"))
|
||||
.check(jsonPath("$.transactionDate").saveAs("txtDate"))
|
||||
.check(jsonPath("$.customerId").saveAs("custId")))
|
||||
.pause(1)
|
||||
|
||||
.exec(http("get_reward")
|
||||
.get("/rewards/find/${custId}")
|
||||
.check(jsonPath("$.id").saveAs("rwdId")))
|
||||
.pause(1)
|
||||
.check(jsonPath("$.id").optional.saveAs("rwdId")))
|
||||
|
||||
.doIf("${rwdId.isUndefined()}"){
|
||||
exec(http("rewards_add")
|
||||
.post("/rewards/add")
|
||||
.body(StringBody("""{ "customerId": "${custId}" }""")).asJson
|
||||
.body(StringBody("""{"customerId":${custId}}""")).asJson
|
||||
.check(jsonPath("$.id").saveAs("rwdId")))
|
||||
}
|
||||
|
||||
.exec(http("transactions_add")
|
||||
.exec(http("transactions_update")
|
||||
.post("/transactions/add/")
|
||||
.body(StringBody("""{ "customerRewardsId":"${rwdId}","customerId":"${custId}","transactionDate":"${txtDate}" }""")).asJson)
|
||||
.pause(1)
|
||||
.body(StringBody("""{"customerRewardsId":${rwdId},"customerId":${custId},"transactionDate":"${txtDate}" }""")).asJson)
|
||||
|
||||
.exec(http("get_reward")
|
||||
.exec(http("get_transactions")
|
||||
.get("/transactions/findAll/${rwdId}"))
|
||||
|
||||
.exec(_.removeAll("txnId", "txtDate", "custId", "rwdId"))
|
||||
}
|
||||
setUp(
|
||||
scn.inject(atOnceUsers(100))
|
||||
).protocols(httpProtocol)
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -16,7 +16,7 @@
|
||||
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
|
||||
<elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
|
||||
<boolProp name="LoopController.continue_forever">false</boolProp>
|
||||
<stringProp name="LoopController.loops">10</stringProp>
|
||||
<stringProp name="LoopController.loops">1000</stringProp>
|
||||
</elementProp>
|
||||
<stringProp name="ThreadGroup.num_threads">100</stringProp>
|
||||
<stringProp name="ThreadGroup.ramp_time">0</stringProp>
|
||||
@@ -200,7 +200,7 @@
|
||||
</HTTPSamplerProxy>
|
||||
<hashTree/>
|
||||
<RandomVariableConfig guiclass="TestBeanGUI" testclass="RandomVariableConfig" testname="Random Variable" enabled="true">
|
||||
<stringProp name="maximumValue">10000</stringProp>
|
||||
<stringProp name="maximumValue">9223372036854775806</stringProp>
|
||||
<stringProp name="minimumValue">1</stringProp>
|
||||
<stringProp name="outputFormat"></stringProp>
|
||||
<boolProp name="perThread">false</boolProp>
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
grinder.script = grinder.py
|
||||
grinder.threads = 100
|
||||
grinder.processes = 1
|
||||
grinder.runs = 10
|
||||
grinder.runs = 1000
|
||||
grinder.logDirectory = /logs
|
||||
|
||||
+3
-1
@@ -24,6 +24,7 @@ random=java.util.Random()
|
||||
|
||||
class TestRunner:
|
||||
def __call__(self):
|
||||
|
||||
customerId = str(random.nextInt());
|
||||
|
||||
result = request1.POST("http://localhost:8080/transactions/add", "{"'"customerRewardsId"'":null,"'"customerId"'":"+ customerId + ","'"transactionDate"'":null}")
|
||||
@@ -37,4 +38,5 @@ class TestRunner:
|
||||
rwdId = parseJsonString(result.getText(), "id")
|
||||
|
||||
result = request1.POST("http://localhost:8080/transactions/add", "{"'"id"'":" + txnId + ","'"customerRewardsId"'":" + rwdId + ","'"customerId"'":"+ customerId + ","'"transactionDate"'":null}")
|
||||
result = request1.GET("http://localhost:8080/transactions/findAll/" + rwdId)
|
||||
result = request1.GET("http://localhost:8080/transactions/findAll/" + rwdId)
|
||||
|
||||
|
||||
@@ -5,4 +5,8 @@
|
||||
- [Mockito Strict Stubbing and The UnnecessaryStubbingException](https://www.baeldung.com/mockito-unnecessary-stubbing-exception)
|
||||
- [Mockito and Fluent APIs](https://www.baeldung.com/mockito-fluent-apis)
|
||||
- [Mocking the ObjectMapper readValue() Method](https://www.baeldung.com/mockito-mock-jackson-read-value)
|
||||
- [Introduction to Mockito’s AdditionalAnswers](https://www.baeldung.com/mockito-additionalanswers)
|
||||
- [Introduction to Mockito’s AdditionalAnswers](https://www.baeldung.com/mockito-additionalanswers)
|
||||
- [Mockito – Using Spies](https://www.baeldung.com/mockito-spy)
|
||||
- [Using Mockito ArgumentCaptor](https://www.baeldung.com/mockito-argumentcaptor)
|
||||
- [Difference Between when() and doXxx() Methods in Mockito](https://www.baeldung.com/java-mockito-when-vs-do)
|
||||
- [Overview of Mockito MockSettings](https://www.baeldung.com/mockito-mocksettings)
|
||||
|
||||
@@ -30,7 +30,6 @@
|
||||
|
||||
<properties>
|
||||
<mockito.version>2.21.0</mockito.version>
|
||||
<jackson.version>2.10.3</jackson.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public enum AuthenticationStatus {
|
||||
AUTHENTICATED,
|
||||
NOT_AUTHENTICATED,
|
||||
ERROR
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public class Credentials {
|
||||
private final String name;
|
||||
private final String password;
|
||||
private final String key;
|
||||
|
||||
public Credentials(String name, String password, String key) {
|
||||
this.name = name;
|
||||
this.password = password;
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public interface DeliveryPlatform {
|
||||
|
||||
void deliver(Email email);
|
||||
|
||||
String getServiceStatus();
|
||||
|
||||
AuthenticationStatus authenticate(Credentials credentials);
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public class Email {
|
||||
|
||||
private String address;
|
||||
private String subject;
|
||||
private String body;
|
||||
private Format format;
|
||||
|
||||
public Email(String address, String subject, String body) {
|
||||
this.address = address;
|
||||
this.subject = subject;
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public void setAddress(String address) {
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getSubject() {
|
||||
return subject;
|
||||
}
|
||||
|
||||
public void setSubject(String subject) {
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public void setBody(String body) {
|
||||
this.body = body;
|
||||
}
|
||||
|
||||
public Format getFormat() {
|
||||
return format;
|
||||
}
|
||||
|
||||
public void setFormat(Format format) {
|
||||
this.format = format;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public class EmailService {
|
||||
|
||||
private DeliveryPlatform platform;
|
||||
|
||||
public EmailService(DeliveryPlatform platform) {
|
||||
this.platform = platform;
|
||||
}
|
||||
|
||||
public void send(String to, String subject, String body, boolean html) {
|
||||
Format format = Format.TEXT_ONLY;
|
||||
if (html) {
|
||||
format = Format.HTML;
|
||||
}
|
||||
Email email = new Email(to, subject, body);
|
||||
email.setFormat(format);
|
||||
platform.deliver(email);
|
||||
}
|
||||
|
||||
public ServiceStatus checkServiceStatus() {
|
||||
if (platform.getServiceStatus().equals("OK")) {
|
||||
return ServiceStatus.UP;
|
||||
} else {
|
||||
return ServiceStatus.DOWN;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean authenticatedSuccessfully(Credentials credentials) {
|
||||
if (platform.authenticate(credentials).equals(AuthenticationStatus.AUTHENTICATED)) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public enum Format {
|
||||
TEXT_ONLY,
|
||||
HTML
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
public enum ServiceStatus {
|
||||
UP,
|
||||
DOWN,
|
||||
AUTHENTICATED
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.mockito.mocksettings;
|
||||
|
||||
public abstract class AbstractCoffee {
|
||||
|
||||
protected String name;
|
||||
|
||||
protected AbstractCoffee(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
protected String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.mockito.mocksettings;
|
||||
|
||||
public class SimpleService {
|
||||
|
||||
public SimpleService(SpecialInterface special) {
|
||||
Runnable runnable = (Runnable) special;
|
||||
runnable.run();
|
||||
}
|
||||
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.mockito.mocksettings;
|
||||
|
||||
public interface SpecialInterface {
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.baeldung.mockito.whenvsdomethods;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
public interface Employee {
|
||||
|
||||
String greet();
|
||||
|
||||
void work(DayOfWeek day);
|
||||
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package com.baeldung.mockito.whenvsdomethods;
|
||||
|
||||
public class IAmOnHolidayException extends RuntimeException {
|
||||
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.baeldung.mockito.argumentcaptor;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class EmailServiceUnitTest {
|
||||
|
||||
@Mock
|
||||
DeliveryPlatform platform;
|
||||
|
||||
@InjectMocks
|
||||
EmailService emailService;
|
||||
|
||||
@Captor
|
||||
ArgumentCaptor<Email> emailCaptor;
|
||||
|
||||
@Captor
|
||||
ArgumentCaptor<Credentials> credentialsCaptor;
|
||||
|
||||
@Test
|
||||
public void whenDoesNotSupportHtml_expectTextOnlyEmailFormat() {
|
||||
String to = "info@baeldung.com";
|
||||
String subject = "Using ArgumentCaptor";
|
||||
String body = "Hey, let'use ArgumentCaptor";
|
||||
|
||||
emailService.send(to, subject, body, false);
|
||||
|
||||
Mockito.verify(platform).deliver(emailCaptor.capture());
|
||||
Email emailCaptorValue = emailCaptor.getValue();
|
||||
assertEquals(Format.TEXT_ONLY, emailCaptorValue.getFormat());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenDoesSupportHtml_expectHTMLEmailFormat() {
|
||||
String to = "info@baeldung.com";
|
||||
String subject = "Using ArgumentCaptor";
|
||||
String body = "<html><body>Hey, let'use ArgumentCaptor</body></html>";
|
||||
|
||||
emailService.send(to, subject, body, true);
|
||||
|
||||
Mockito.verify(platform).deliver(emailCaptor.capture());
|
||||
Email value = emailCaptor.getValue();
|
||||
assertEquals(Format.HTML, value.getFormat());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceRunning_expectUpResponse() {
|
||||
Mockito.when(platform.getServiceStatus()).thenReturn("OK");
|
||||
|
||||
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
||||
|
||||
assertEquals(ServiceStatus.UP, serviceStatus);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceNotRunning_expectDownResponse() {
|
||||
Mockito.when(platform.getServiceStatus()).thenReturn("Error");
|
||||
|
||||
ServiceStatus serviceStatus = emailService.checkServiceStatus();
|
||||
|
||||
assertEquals(ServiceStatus.DOWN, serviceStatus);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingArgumentMatcherForValidCredentials_expectTrue() {
|
||||
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
||||
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
||||
|
||||
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingArgumentCaptorForValidCredentials_expectTrue() {
|
||||
Credentials credentials = new Credentials("baeldung", "correct_password", "correct_key");
|
||||
Mockito.when(platform.authenticate(credentialsCaptor.capture())).thenReturn(AuthenticationStatus.AUTHENTICATED);
|
||||
|
||||
assertTrue(emailService.authenticatedSuccessfully(credentials));
|
||||
assertEquals(credentials, credentialsCaptor.getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotAuthenticated_expectFalse() {
|
||||
Credentials credentials = new Credentials("baeldung", "incorrect_password", "incorrect_key");
|
||||
Mockito.when(platform.authenticate(Mockito.eq(credentials))).thenReturn(AuthenticationStatus.NOT_AUTHENTICATED);
|
||||
|
||||
assertFalse(emailService.authenticatedSuccessfully(credentials));
|
||||
}
|
||||
}
|
||||
+12
-17
@@ -1,5 +1,16 @@
|
||||
package com.baeldung.mockito.fluentapi;
|
||||
|
||||
import com.baeldung.mockito.fluentapi.Pizza.PizzaBuilder;
|
||||
import com.baeldung.mockito.fluentapi.Pizza.PizzaSize;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
@@ -8,18 +19,7 @@ import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Answers;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Captor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
import com.baeldung.mockito.fluentapi.Pizza.PizzaBuilder;
|
||||
import com.baeldung.mockito.fluentapi.Pizza.PizzaSize;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class PizzaServiceUnitTest {
|
||||
|
||||
@Mock
|
||||
@@ -33,11 +33,6 @@ public class PizzaServiceUnitTest {
|
||||
@Captor
|
||||
private ArgumentCaptor<Pizza.PizzaSize> sizeCaptor;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTraditonalMocking_whenServiceInvoked_thenPizzaIsBuilt() {
|
||||
PizzaBuilder nameBuilder = Mockito.mock(Pizza.PizzaBuilder.class);
|
||||
|
||||
+10
-15
@@ -1,19 +1,19 @@
|
||||
package com.baeldung.mockito.java8;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ArgumentMatcherWithLambdaUnitTest {
|
||||
|
||||
@InjectMocks
|
||||
@@ -36,9 +36,4 @@ public class ArgumentMatcherWithLambdaUnitTest {
|
||||
assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(linda));
|
||||
assertFalse(unemploymentService.personIsEntitledToUnemploymentSupport(peter));
|
||||
}
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
}
|
||||
|
||||
+7
-7
@@ -1,8 +1,12 @@
|
||||
package com.baeldung.mockito.java8;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.*;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@@ -11,6 +15,7 @@ import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class ArgumentMatcherWithoutLambdaUnitTest {
|
||||
|
||||
private class PeterArgumentMatcher implements ArgumentMatcher<Person> {
|
||||
@@ -43,9 +48,4 @@ public class ArgumentMatcherWithoutLambdaUnitTest {
|
||||
assertTrue(unemploymentService.personIsEntitledToUnemploymentSupport(linda));
|
||||
assertFalse(unemploymentService.personIsEntitledToUnemploymentSupport(peter));
|
||||
}
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
}
|
||||
|
||||
+3
-3
@@ -2,9 +2,10 @@ package com.baeldung.mockito.java8;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -13,6 +14,7 @@ import static org.junit.Assert.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CustomAnswerWithLambdaUnitTest {
|
||||
|
||||
@InjectMocks
|
||||
@@ -37,8 +39,6 @@ public class CustomAnswerWithLambdaUnitTest {
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
|
||||
when(jobService.listJobs(any(Person.class))).then((i) ->
|
||||
Stream.of(new JobPosition("Teacher"))
|
||||
.filter(p -> ((Person) i.getArgument(0)).getName().equals("Peter")));
|
||||
|
||||
+3
-4
@@ -2,10 +2,11 @@ package com.baeldung.mockito.java8;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
import org.mockito.invocation.InvocationOnMock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
@@ -15,7 +16,7 @@ import static org.junit.Assert.assertFalse;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class CustomAnswerWithoutLambdaUnitTest {
|
||||
|
||||
private class PersonAnswer implements Answer<Stream<JobPosition>> {
|
||||
@@ -54,8 +55,6 @@ public class CustomAnswerWithoutLambdaUnitTest {
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
|
||||
when(jobService.listJobs(any(Person.class))).then(new PersonAnswer());
|
||||
}
|
||||
}
|
||||
|
||||
+9
-13
@@ -1,18 +1,19 @@
|
||||
package com.baeldung.mockito.java8;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Mockito.doCallRealMethod;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Mockito;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class JobServiceUnitTest {
|
||||
@Mock
|
||||
private JobService jobService;
|
||||
@@ -36,9 +37,4 @@ public class JobServiceUnitTest {
|
||||
|
||||
assertTrue(jobService.assignJobPosition(person, new JobPosition()));
|
||||
}
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
}
|
||||
|
||||
+10
-14
@@ -1,19 +1,20 @@
|
||||
package com.baeldung.mockito.java8;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.mockito.Matchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class UnemploymentServiceImplUnitTest {
|
||||
@Mock
|
||||
private JobService jobService;
|
||||
@@ -54,9 +55,4 @@ public class UnemploymentServiceImplUnitTest {
|
||||
// This will fail when Mockito 1 is used
|
||||
assertFalse(unemploymentService.searchJob(person, "").isPresent());
|
||||
}
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
}
|
||||
|
||||
+12
-16
@@ -1,21 +1,22 @@
|
||||
package com.baeldung.mockito.misusing;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.exceptions.misusing.UnnecessaryStubbingException;
|
||||
import org.mockito.junit.MockitoJUnit;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
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;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockitoUnecessaryStubUnitTest {
|
||||
|
||||
@Rule
|
||||
@@ -25,11 +26,6 @@ public class MockitoUnecessaryStubUnitTest {
|
||||
@Mock
|
||||
private ArrayList<String> mockList;
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUnusedStub_whenInvokingGetThenThrowUnnecessaryStubbingException() {
|
||||
rule.expectedFailure(UnnecessaryStubbingException.class);
|
||||
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.mockito.mocksettings;
|
||||
|
||||
import static org.mockito.Answers.RETURNS_SMART_NULLS;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.mockito.Answers.CALLS_REAL_METHODS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.mockito.Mockito.withSettings;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.mockito.exceptions.verification.SmartNullPointerException;
|
||||
import org.mockito.junit.MockitoJUnitRunner;
|
||||
|
||||
import com.baeldung.mockito.fluentapi.Pizza;
|
||||
import com.baeldung.mockito.fluentapi.PizzaService;
|
||||
|
||||
@RunWith(MockitoJUnitRunner.class)
|
||||
public class MockSettingsUnitTest {
|
||||
|
||||
@Test(expected = SmartNullPointerException.class)
|
||||
public void whenServiceMockedWithSmartNulls_thenExceptionHasExtraInfo() {
|
||||
PizzaService service = mock(PizzaService.class, withSettings().defaultAnswer(RETURNS_SMART_NULLS));
|
||||
Pizza pizza = service.orderHouseSpecial();
|
||||
pizza.getSize();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceMockedWithNameAndVerboseLogging_thenLogsMethodInvocations() {
|
||||
PizzaService service = mock(PizzaService.class, withSettings().name("pizzaServiceMock")
|
||||
.verboseLogging());
|
||||
|
||||
Pizza pizza = mock(Pizza.class);
|
||||
when(service.orderHouseSpecial()).thenReturn(pizza);
|
||||
|
||||
service.orderHouseSpecial();
|
||||
|
||||
verify(service).orderHouseSpecial();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenServiceMockedWithExtraInterfaces_thenConstructorSuccess() {
|
||||
SpecialInterface specialMock = mock(SpecialInterface.class, withSettings().extraInterfaces(Runnable.class));
|
||||
new SimpleService(specialMock);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMockSetupWithConstructor_thenConstructorIsInvoked() {
|
||||
AbstractCoffee coffeeSpy = mock(AbstractCoffee.class, withSettings().useConstructor("espresso")
|
||||
.defaultAnswer(CALLS_REAL_METHODS));
|
||||
|
||||
assertEquals("Coffee name: ", "espresso", coffeeSpy.getName());
|
||||
}
|
||||
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.baeldung.mockito.whenvsdomethods;
|
||||
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
import static org.junit.Assert.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.BDDMockito.given;
|
||||
import static org.mockito.BDDMockito.willThrow;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockitoAnnotations;
|
||||
|
||||
public class WhenVsDoMethodsUnitTest {
|
||||
|
||||
@Mock
|
||||
private Employee employee;
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
MockitoAnnotations.initMocks(this);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonVoidMethod_callingWhen_shouldConfigureBehavior() {
|
||||
// given
|
||||
when(employee.greet()).thenReturn("Hello");
|
||||
|
||||
// when
|
||||
String greeting = employee.greet();
|
||||
|
||||
// then
|
||||
assertThat(greeting, is("Hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonVoidMethod_callingDoReturn_shouldConfigureBehavior() {
|
||||
// given
|
||||
doReturn("Hello").when(employee).greet();
|
||||
|
||||
// when
|
||||
String greeting = employee.greet();
|
||||
|
||||
// then
|
||||
assertThat(greeting, is("Hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenVoidMethod_callingDoThrow_shouldConfigureBehavior() {
|
||||
// given
|
||||
doThrow(new IAmOnHolidayException()).when(employee).work(DayOfWeek.SUNDAY);
|
||||
|
||||
// when
|
||||
Executable workCall = () -> employee.work(DayOfWeek.SUNDAY);
|
||||
|
||||
// then
|
||||
assertThrows(IAmOnHolidayException.class, workCall);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenNonVoidMethod_callingGiven_shouldConfigureBehavior() {
|
||||
// given
|
||||
given(employee.greet()).willReturn("Hello");
|
||||
|
||||
// when
|
||||
String greeting = employee.greet();
|
||||
|
||||
// then
|
||||
assertThat(greeting, is("Hello"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenVoidMethod_callingWillThrow_shouldConfigureBehavior() {
|
||||
// given
|
||||
willThrow(new IAmOnHolidayException()).given(employee).work(DayOfWeek.SUNDAY);
|
||||
|
||||
// when
|
||||
Executable workCall = () -> employee.work(DayOfWeek.SUNDAY);
|
||||
|
||||
// then
|
||||
assertThrows(IAmOnHolidayException.class, workCall);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/target/
|
||||
/.settings/
|
||||
/.classpath
|
||||
/.project
|
||||
@@ -0,0 +1,3 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Mocking Static Methods With Mockito](https://www.baeldung.com/mockito-mock-static-methods)
|
||||
@@ -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>mockito-3</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>mockito-3</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.mockito</groupId>
|
||||
<artifactId>mockito-inline</artifactId>
|
||||
<version>${mockito.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<mockito.version>3.8.0</mockito.version>
|
||||
<assertj.version>3.8.0</assertj.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.mockito.mockedstatic;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.IntStream;
|
||||
|
||||
public class StaticUtils {
|
||||
|
||||
private StaticUtils() {
|
||||
}
|
||||
|
||||
public static List<Integer> range(int start, int end) {
|
||||
return IntStream.range(start, end)
|
||||
.boxed()
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public static String name() {
|
||||
return "Baeldung";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.mockito.mockedstatic;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
class MockedStaticUnitTest {
|
||||
|
||||
@Test
|
||||
void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
|
||||
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
||||
|
||||
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
|
||||
utilities.when(StaticUtils::name).thenReturn("Eugen");
|
||||
assertThat(StaticUtils.name()).isEqualTo("Eugen");
|
||||
}
|
||||
|
||||
assertThat(StaticUtils.name()).isEqualTo("Baeldung");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
|
||||
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
||||
|
||||
try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
|
||||
utilities.when(() -> StaticUtils.range(2, 6))
|
||||
.thenReturn(Arrays.asList(10, 11, 12));
|
||||
|
||||
assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12);
|
||||
}
|
||||
|
||||
assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -12,5 +12,4 @@
|
||||
- [Mocking Void Methods with Mockito](https://www.baeldung.com/mockito-void-methods)
|
||||
- [Mock Final Classes and Methods with Mockito](https://www.baeldung.com/mockito-final)
|
||||
- [Testing Callbacks with Mockito](https://www.baeldung.com/mockito-callbacks)
|
||||
- [Mockito – Using Spies](https://www.baeldung.com/mockito-spy)
|
||||
- [Quick Guide to BDDMockito](https://www.baeldung.com/bdd-mockito)
|
||||
|
||||
-46
@@ -76,52 +76,6 @@ public class MockitoAnnotationUnitTest {
|
||||
assertEquals(100, spiedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSpyingOnList_thenCorrect() {
|
||||
List<String> list = new ArrayList<String>();
|
||||
List<String> spyList = Mockito.spy(list);
|
||||
|
||||
spyList.add("one");
|
||||
spyList.add("two");
|
||||
|
||||
Mockito.verify(spyList).add("one");
|
||||
Mockito.verify(spyList).add("two");
|
||||
|
||||
assertEquals(2, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
|
||||
spiedList.add("one");
|
||||
spiedList.add("two");
|
||||
|
||||
Mockito.verify(spiedList).add("one");
|
||||
Mockito.verify(spiedList).add("two");
|
||||
|
||||
assertEquals(2, spiedList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenStubASpy_thenStubbed() {
|
||||
List<String> list = new ArrayList<String>();
|
||||
List<String> spyList = Mockito.spy(list);
|
||||
|
||||
assertEquals(0, spyList.size());
|
||||
|
||||
Mockito.doReturn(100).when(spyList).size();
|
||||
assertEquals(100, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreateSpy_thenCreate() {
|
||||
List<String> spyList = Mockito.spy(new ArrayList<>());
|
||||
|
||||
spyList.add("one");
|
||||
Mockito.verify(spyList).add("one");
|
||||
|
||||
assertEquals(1, spyList.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenNotUseCaptorAnnotation_thenCorrect() {
|
||||
final List<String> mockList = Mockito.mock(List.class);
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.0</version>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<parallel>all</parallel>
|
||||
<threadCount>10</threadCount>
|
||||
@@ -45,4 +45,8 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.22.0</version>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<parallel>all</parallel>
|
||||
<useUnlimitedThreads>true</useUnlimitedThreads>
|
||||
@@ -37,4 +37,8 @@
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
+14
-10
@@ -15,34 +15,38 @@
|
||||
|
||||
<modules>
|
||||
<module>assertion-libraries</module>
|
||||
<module>cucumber</module>
|
||||
<module>easy-random</module>
|
||||
<module>easymock</module>
|
||||
<module>gatling</module>
|
||||
<module>groovy-spock</module>
|
||||
<module>hamcrest</module>
|
||||
<module>junit-4</module>
|
||||
<module>junit-5-advanced</module>
|
||||
<module>junit-5-basics</module>
|
||||
<module>junit-5</module>
|
||||
<module>junit5-annotations</module>
|
||||
<module>junit5-migration</module>
|
||||
<module>load-testing-comparison</module>
|
||||
<module>mockito</module>
|
||||
<module>mockito-2</module>
|
||||
<module>hamcrest</module>
|
||||
<module>mockito-3</module>
|
||||
<module>mockito</module>
|
||||
<module>mocks</module>
|
||||
<module>mockserver</module>
|
||||
<module>parallel-tests-junit</module>
|
||||
<module>powermock</module>
|
||||
<module>rest-assured</module>
|
||||
<module>rest-testing</module>
|
||||
<module>selenium-junit-testng</module>
|
||||
<module>spring-testing-2</module>
|
||||
<module>spring-testing</module>
|
||||
<module>test-containers</module>
|
||||
<module>testing-assertions</module>
|
||||
<module>testng</module>
|
||||
<module>junit-5-basics</module>
|
||||
<module>easymock</module>
|
||||
<module>junit-5-advanced</module>
|
||||
<module>xmlunit-2</module>
|
||||
<module>junit-4</module>
|
||||
<module>testing-libraries-2</module>
|
||||
<module>testing-libraries</module>
|
||||
<module>powermock</module>
|
||||
<module>cucumber</module>
|
||||
<module>testng</module>
|
||||
<module>xmlunit-2</module>
|
||||
<module>zerocode</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -102,6 +102,7 @@
|
||||
<dependency>
|
||||
<groupId>joda-time</groupId>
|
||||
<artifactId>joda-time</artifactId>
|
||||
<version>${joda-time.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
|
||||
@@ -65,13 +65,13 @@
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>info.cukes</groupId>
|
||||
<groupId>io.cucumber</groupId>
|
||||
<artifactId>cucumber-java</artifactId>
|
||||
<version>${cucumber.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>info.cukes</groupId>
|
||||
<groupId>io.cucumber</groupId>
|
||||
<artifactId>cucumber-junit</artifactId>
|
||||
<version>${cucumber.version}</version>
|
||||
</dependency>
|
||||
@@ -105,56 +105,44 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<configuration>
|
||||
<parallel>classes</parallel>
|
||||
<threadCount>4</threadCount>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>com.github.temyers</groupId>
|
||||
<artifactId>cucumber-jvm-parallel-plugin</artifactId>
|
||||
<version>5.0.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generateRunners</id>
|
||||
<phase>generate-test-sources</phase>
|
||||
<goals>
|
||||
<goal>generateRunners</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<glue>
|
||||
<package>com.baeldung.rest.cucumber</package>
|
||||
</glue>
|
||||
<featuresDirectory>src/test/resources/Feature/</featuresDirectory>
|
||||
<parallelScheme>SCENARIO</parallelScheme>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
|
||||
</build>
|
||||
|
||||
<profiles>
|
||||
<profile>
|
||||
<id>parallel</id>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>CucumberIntegrationTest.java</include>
|
||||
</includes>
|
||||
<parallel>methods</parallel>
|
||||
<threadCount>2</threadCount>
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</profile>
|
||||
</profiles>
|
||||
|
||||
<properties>
|
||||
<!-- util -->
|
||||
<guava.version>19.0</guava.version>
|
||||
|
||||
<!-- testing -->
|
||||
<rest-assured.version>2.9.0</rest-assured.version>
|
||||
<cucumber.version>1.2.5</cucumber.version>
|
||||
<cucumber.version>6.8.0</cucumber.version>
|
||||
<wiremock.version>2.21.0</wiremock.version>
|
||||
<karate.version>0.6.1</karate.version>
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
Feature: Testing a REST API
|
||||
Users should be able to submit GET and POST requests to a web service, represented by WireMock
|
||||
|
||||
Scenario: Data Upload to a web service
|
||||
When users upload data on a project
|
||||
Then the server should handle it and return a success status
|
||||
|
||||
Scenario: Data retrieval from a web service
|
||||
When users want to get information on the Cucumber project
|
||||
Then the requested data is returned
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
package com.baeldung.rest.cucumber;
|
||||
|
||||
import io.cucumber.junit.Cucumber;
|
||||
import io.cucumber.junit.CucumberOptions;
|
||||
import org.junit.runner.RunWith;
|
||||
import cucumber.api.CucumberOptions;
|
||||
import cucumber.api.junit.Cucumber;
|
||||
|
||||
@RunWith(Cucumber.class)
|
||||
@CucumberOptions(features = "classpath:Feature")
|
||||
|
||||
+6
-5
@@ -20,6 +20,8 @@ import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.Scanner;
|
||||
|
||||
import io.cucumber.java.en.Then;
|
||||
import io.cucumber.java.en.When;
|
||||
import org.apache.http.HttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
@@ -29,8 +31,6 @@ import org.apache.http.impl.client.HttpClients;
|
||||
|
||||
import com.github.tomakehurst.wiremock.WireMockServer;
|
||||
|
||||
import cucumber.api.java.en.Then;
|
||||
import cucumber.api.java.en.When;
|
||||
|
||||
public class StepDefinition {
|
||||
|
||||
@@ -66,7 +66,8 @@ public class StepDefinition {
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
@When("^users want to get information on the (.+) project$")
|
||||
// @When("^users want to get information on the '(.+)' project$")
|
||||
@When("users want to get information on the {string} project")
|
||||
public void usersGetInformationOnAProject(String projectName) throws IOException {
|
||||
wireMockServer.start();
|
||||
|
||||
@@ -86,11 +87,11 @@ public class StepDefinition {
|
||||
wireMockServer.stop();
|
||||
}
|
||||
|
||||
@Then("^the server should handle it and return a success status$")
|
||||
@Then("the server should handle it and return a success status")
|
||||
public void theServerShouldReturnASuccessStatus() {
|
||||
}
|
||||
|
||||
@Then("^the requested data is returned$")
|
||||
@Then("the requested data is returned")
|
||||
public void theRequestedDataIsReturned() {
|
||||
}
|
||||
|
||||
|
||||
@@ -6,5 +6,5 @@ Feature: Testing a REST API
|
||||
Then the server should handle it and return a success status
|
||||
|
||||
Scenario: Data retrieval from a web service
|
||||
When users want to get information on the Cucumber project
|
||||
When users want to get information on the 'Cucumber' project
|
||||
Then the requested data is returned
|
||||
@@ -4,3 +4,4 @@
|
||||
- [Testing with Selenium/WebDriver and the Page Object Pattern](http://www.baeldung.com/selenium-webdriver-page-object)
|
||||
- [Using Cookies With Selenium WebDriver in Java](https://www.baeldung.com/java-selenium-webdriver-cookies)
|
||||
- [Clicking Elements in Selenium using JavaScript](https://www.baeldung.com/java-selenium-javascript)
|
||||
- [Taking Screenshots With Selenium WebDriver](https://www.baeldung.com/java-selenium-screenshots)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
.idea/**
|
||||
target/**
|
||||
*.iml
|
||||
@@ -0,0 +1,5 @@
|
||||
## Relevant Articles:
|
||||
|
||||
- [Guide to @DynamicPropertySource in Spring](https://www.baeldung.com/spring-dynamicpropertysource)
|
||||
- [Concurrent Test Execution in Spring 5](https://www.baeldung.com/spring-5-concurrent-tests)
|
||||
- [Spring 5 Testing with @EnabledIf Annotation](https://www.baeldung.com/spring-5-enabledIf)
|
||||
@@ -0,0 +1,77 @@
|
||||
<?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>spring-testing-2</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>spring-testing-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</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-data-jpa</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.h2database</groupId>
|
||||
<artifactId>h2</artifactId>
|
||||
<version>${h2.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.postgresql</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<scope>runtime</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Test containers only dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>postgresql</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.testcontainers</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${testcontainers.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Test containers only dependencies -->
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<!-- this surefire configuration allows concurrent execution;
|
||||
do not remove -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>${maven-surefire-plugin.version}</version>
|
||||
<configuration>
|
||||
<parallel>methods</parallel>
|
||||
<useUnlimitedThreads>true</useUnlimitedThreads>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<testcontainers.version>1.12.2</testcontainers.version>
|
||||
</properties>
|
||||
</project>
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.dynamicproperties;
|
||||
|
||||
import javax.persistence.Entity;
|
||||
import javax.persistence.GeneratedValue;
|
||||
import javax.persistence.Id;
|
||||
import javax.persistence.Table;
|
||||
|
||||
import static javax.persistence.GenerationType.IDENTITY;
|
||||
|
||||
@Entity
|
||||
@Table(name = "articles")
|
||||
public class Article {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = IDENTITY)
|
||||
private Long id;
|
||||
|
||||
private String title;
|
||||
|
||||
private String content;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Long id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getContent() {
|
||||
return content;
|
||||
}
|
||||
|
||||
public void setContent(String content) {
|
||||
this.content = content;
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.dynamicproperties;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
public interface ArticleRepository extends JpaRepository<Article, Long> {
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.dynamicproperties;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class DynamicPropertiesApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(DynamicPropertiesApplication.class, args);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.concurrent;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@ContextConfiguration(classes = Spring5JUnit4ConcurrentIntegrationTest.SimpleConfiguration.class)
|
||||
public class Spring5JUnit4ConcurrentIntegrationTest implements ApplicationContextAware, InitializingBean {
|
||||
|
||||
@Configuration
|
||||
public static class SimpleConfiguration {
|
||||
}
|
||||
|
||||
private ApplicationContext applicationContext;
|
||||
|
||||
private boolean beanInitialized = false;
|
||||
|
||||
@Override
|
||||
public final void afterPropertiesSet() throws Exception {
|
||||
this.beanInitialized = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public final void setApplicationContext(final ApplicationContext applicationContext) throws BeansException {
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void verifyApplicationContextSet() throws InterruptedException {
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
assertNotNull("The application context should have been set due to ApplicationContextAware semantics.", this.applicationContext);
|
||||
}
|
||||
|
||||
@Test
|
||||
public final void verifyBeanInitialized() throws InterruptedException {
|
||||
TimeUnit.SECONDS.sleep(2);
|
||||
assertTrue("This test bean should have been initialized due to InitializingBean semantics.", this.beanInitialized);
|
||||
}
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.dynamicproperties;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest
|
||||
@Testcontainers
|
||||
@ActiveProfiles("pg")
|
||||
public class ArticleLiveTest {
|
||||
|
||||
@Container
|
||||
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:11")
|
||||
.withDatabaseName("prop")
|
||||
.withUsername("postgres")
|
||||
.withPassword("pass")
|
||||
.withExposedPorts(5432);
|
||||
|
||||
@Autowired
|
||||
private ArticleRepository articleRepository;
|
||||
|
||||
@DynamicPropertySource
|
||||
static void registerPgProperties(DynamicPropertyRegistry registry) {
|
||||
registry.add("spring.datasource.url",
|
||||
() -> String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()));
|
||||
registry.add("spring.datasource.username", () -> "postgres");
|
||||
registry.add("spring.datasource.password", () -> "pass");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenAnArticle_whenPersisted_thenCanBeFoundInTheDb() {
|
||||
Article article = new Article();
|
||||
article.setTitle("A Guide to @DynamicPropertySource in Spring");
|
||||
article.setContent("Today's applications...");
|
||||
|
||||
articleRepository.save(article);
|
||||
Article persisted = articleRepository.findAll().get(0);
|
||||
assertThat(persisted.getId()).isNotNull();
|
||||
assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring");
|
||||
assertThat(persisted.getContent()).isEqualTo("Today's applications...");
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.dynamicproperties;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("pg")
|
||||
@ExtendWith(PostgreSQLExtension.class)
|
||||
public class ArticleTestFixtureLiveTest {
|
||||
|
||||
@Autowired
|
||||
private ArticleRepository articleRepository;
|
||||
|
||||
@Test
|
||||
void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() {
|
||||
Article article = new Article();
|
||||
article.setTitle("A Guide to @DynamicPropertySource in Spring");
|
||||
article.setContent("Today's applications...");
|
||||
|
||||
articleRepository.save(article);
|
||||
Article persisted = articleRepository.findAll().get(0);
|
||||
assertThat(persisted.getId()).isNotNull();
|
||||
assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring");
|
||||
assertThat(persisted.getContent()).isEqualTo("Today's applications...");
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.dynamicproperties;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.util.TestPropertyValues;
|
||||
import org.springframework.context.ApplicationContextInitializer;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@SpringBootTest
|
||||
@Testcontainers
|
||||
@ActiveProfiles("pg")
|
||||
@ContextConfiguration(initializers = ArticleTraditionalLiveTest.EnvInitializer.class)
|
||||
class ArticleTraditionalLiveTest {
|
||||
|
||||
@Container
|
||||
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:11")
|
||||
.withDatabaseName("prop")
|
||||
.withUsername("postgres")
|
||||
.withPassword("pass")
|
||||
.withExposedPorts(5432);
|
||||
|
||||
static class EnvInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
|
||||
|
||||
@Override
|
||||
public void initialize(ConfigurableApplicationContext applicationContext) {
|
||||
TestPropertyValues.of(
|
||||
String.format("spring.datasource.url=jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort()),
|
||||
"spring.datasource.username=postgres",
|
||||
"spring.datasource.password=pass"
|
||||
).applyTo(applicationContext);
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private ArticleRepository articleRepository;
|
||||
|
||||
@Test
|
||||
void givenAnArticle_whenPersisted_thenShouldBeAbleToReadIt() {
|
||||
Article article = new Article();
|
||||
article.setTitle("A Guide to @DynamicPropertySource in Spring");
|
||||
article.setContent("Today's applications...");
|
||||
|
||||
articleRepository.save(article);
|
||||
Article persisted = articleRepository.findAll().get(0);
|
||||
assertThat(persisted.getId()).isNotNull();
|
||||
assertThat(persisted.getTitle()).isEqualTo("A Guide to @DynamicPropertySource in Spring");
|
||||
assertThat(persisted.getContent()).isEqualTo("Today's applications...");
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.dynamicproperties;
|
||||
|
||||
import org.junit.jupiter.api.extension.AfterAllCallback;
|
||||
import org.junit.jupiter.api.extension.BeforeAllCallback;
|
||||
import org.junit.jupiter.api.extension.ExtensionContext;
|
||||
import org.testcontainers.containers.PostgreSQLContainer;
|
||||
|
||||
public class PostgreSQLExtension implements BeforeAllCallback, AfterAllCallback {
|
||||
|
||||
private PostgreSQLContainer<?> postgres;
|
||||
|
||||
@Override
|
||||
public void beforeAll(ExtensionContext context) {
|
||||
postgres = new PostgreSQLContainer<>("postgres:11")
|
||||
.withDatabaseName("prop")
|
||||
.withUsername("postgres")
|
||||
.withPassword("pass")
|
||||
.withExposedPorts(5432);
|
||||
|
||||
postgres.start();
|
||||
String jdbcUrl = String.format("jdbc:postgresql://localhost:%d/prop", postgres.getFirstMappedPort());
|
||||
System.setProperty("spring.datasource.url", jdbcUrl);
|
||||
System.setProperty("spring.datasource.username", "postgres");
|
||||
System.setProperty("spring.datasource.password", "pass");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterAll(ExtensionContext context) {
|
||||
postgres.stop();
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.enabledif;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
import org.springframework.test.context.junit.jupiter.EnabledIf;
|
||||
|
||||
@Target({ ElementType.TYPE, ElementType.METHOD })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@EnabledIf(
|
||||
expression = "#{systemProperties['java.version'].startsWith('1.8')}",
|
||||
reason = "Enabled on Java 8"
|
||||
)
|
||||
public @interface EnabledOnJava8 {
|
||||
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.enabledif;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.test.context.TestPropertySource;
|
||||
import org.springframework.test.context.junit.jupiter.DisabledIf;
|
||||
import org.springframework.test.context.junit.jupiter.EnabledIf;
|
||||
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
|
||||
|
||||
@SpringJUnitConfig(Spring5EnabledAnnotationIntegrationTest.Config.class)
|
||||
@TestPropertySource(properties = { "tests.enabled=true" })
|
||||
public class Spring5EnabledAnnotationIntegrationTest {
|
||||
|
||||
@Configuration
|
||||
static class Config {
|
||||
}
|
||||
|
||||
@EnabledIf("true")
|
||||
@Test
|
||||
void givenEnabledIfLiteral_WhenTrue_ThenTestExecuted() {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
@EnabledIf(expression = "${tests.enabled}", loadContext = true)
|
||||
@Test
|
||||
void givenEnabledIfExpression_WhenTrue_ThenTestExecuted() {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
@EnabledIf("#{systemProperties['java.version'].startsWith('1.8')}")
|
||||
@Test
|
||||
void givenEnabledIfSpel_WhenTrue_ThenTestExecuted() {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
@EnabledOnJava8
|
||||
@Test
|
||||
void givenEnabledOnJava8_WhenTrue_ThenTestExecuted() {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
@DisabledIf("#{systemProperties['java.version'].startsWith('1.7')}")
|
||||
@Test
|
||||
void givenDisabledIf_WhenTrue_ThenTestNotExecuted() {
|
||||
assertTrue(true);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
||||
spring.jpa.hibernate.ddl-auto=create-drop
|
||||
@@ -3,16 +3,15 @@
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>spring-testing</artifactId>
|
||||
<version>0.1-SNAPSHOT</version>
|
||||
<name>spring-testing</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-java</artifactId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-java</relativePath>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
@@ -32,25 +31,34 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
<version>LATEST</version>
|
||||
</dependency>
|
||||
|
||||
<!-- test scoped -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<version>LATEST</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.vintage</groupId>
|
||||
<artifactId>junit-vintage-engine</artifactId>
|
||||
<scope>test</scope>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-core</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-core</artifactId>
|
||||
<version>LATEST</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-context</artifactId>
|
||||
<version>LATEST</version>
|
||||
<version>${spring.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
@@ -65,7 +73,6 @@
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-jpa</artifactId>
|
||||
<version>LATEST</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
@@ -116,9 +123,9 @@
|
||||
<!-- testing -->
|
||||
<java-hamcrest.version>2.0.0.0</java-hamcrest.version>
|
||||
<awaitility.version>3.1.6</awaitility.version>
|
||||
<junit.jupiter.version>5.5.0</junit.jupiter.version>
|
||||
<junit.commons.version>1.5.2</junit.commons.version>
|
||||
<spring.version>5.1.4.RELEASE</spring.version>
|
||||
<junit.jupiter.version>5.7.0</junit.jupiter.version>
|
||||
<junit.commons.version>1.7.0</junit.commons.version>
|
||||
<spring.version>5.3.4</spring.version>
|
||||
<javax.servlet-api.version>4.0.1</javax.servlet-api.version>
|
||||
<javax.persistence.version>2.1.1</javax.persistence.version>
|
||||
</properties>
|
||||
|
||||
+4
-5
@@ -1,15 +1,14 @@
|
||||
package com.baeldung.overrideproperties;
|
||||
|
||||
import com.baeldung.overrideproperties.resolver.PropertySourceResolver;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest
|
||||
@ContextConfiguration(initializers = PropertyOverrideContextInitializer.class, classes = Application.class)
|
||||
public class ContextPropertySourceResolverIntegrationTest {
|
||||
|
||||
|
||||
+5
-6
@@ -1,18 +1,17 @@
|
||||
package com.baeldung.overrideproperties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import com.baeldung.overrideproperties.resolver.PropertySourceResolver;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
@EnableWebMvc
|
||||
|
||||
+1
-1
@@ -12,6 +12,6 @@ public class PropertyOverrideContextInitializer implements ApplicationContextIni
|
||||
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
|
||||
TestPropertySourceUtils.addInlinedPropertiesToEnvironment(configurableApplicationContext, "example.firstProperty=" + PROPERTY_FIRST_VALUE);
|
||||
|
||||
TestPropertySourceUtils.addPropertiesFilesToEnvironment(configurableApplicationContext, "context-override-application.properties");
|
||||
TestPropertySourceUtils.addPropertiesFilesToEnvironment(configurableApplicationContext, "classpath:context-override-application.properties");
|
||||
}
|
||||
}
|
||||
|
||||
+7
-7
@@ -1,16 +1,16 @@
|
||||
package com.baeldung.overrideproperties;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import com.baeldung.overrideproperties.resolver.PropertySourceResolver;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@SpringBootTest(properties = { "example.firstProperty=annotation" })
|
||||
@EnableWebMvc
|
||||
public class SpringBootPropertySourceResolverIntegrationTest {
|
||||
@@ -23,8 +23,8 @@ public class SpringBootPropertySourceResolverIntegrationTest {
|
||||
final String firstProperty = propertySourceResolver.getFirstProperty();
|
||||
final String secondProperty = propertySourceResolver.getSecondProperty();
|
||||
|
||||
Assert.assertEquals("annotation", firstProperty);
|
||||
Assert.assertEquals("file", secondProperty);
|
||||
assertEquals("annotation", firstProperty);
|
||||
assertEquals("file", secondProperty);
|
||||
}
|
||||
|
||||
}
|
||||
+5
-6
@@ -1,17 +1,16 @@
|
||||
package com.baeldung.overrideproperties;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit4.SpringRunner;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
||||
|
||||
import com.baeldung.overrideproperties.resolver.PropertySourceResolver;
|
||||
|
||||
@RunWith(SpringRunner.class)
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
@SpringBootTest
|
||||
@EnableWebMvc
|
||||
public class TestResourcePropertySourceResolverIntegrationTest {
|
||||
|
||||
@@ -79,34 +79,6 @@
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
<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-surefire-provider.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.mojo</groupId>
|
||||
<artifactId>exec-maven-plugin</artifactId>
|
||||
<version>${exec-maven-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>java</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.TestLauncher</mainClass>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
@@ -117,7 +89,7 @@
|
||||
<postgresql.version>42.2.6</postgresql.version>
|
||||
<selenium-remote-driver.version>3.141.59</selenium-remote-driver.version>
|
||||
<maven-surefire-plugin.version>2.22.2</maven-surefire-plugin.version>
|
||||
<junit-platform-surefire-provider.version>1.3.2</junit-platform-surefire-provider.version>
|
||||
<junit-platform.version>1.3.2</junit-platform.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Asserting Log Messages With JUnit](https://www.baeldung.com/junit-asserting-logs)
|
||||
- [Assert Two Lists for Equality Ignoring Order in Java](https://www.baeldung.com/java-assert-lists-equality-ignore-order)
|
||||
|
||||
@@ -16,13 +16,43 @@
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>1.2.3</version>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit-jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>3.15.0</version>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hamcrest</groupId>
|
||||
<artifactId>hamcrest-all</artifactId>
|
||||
<version>${hamcrest-all.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>${commons-collections4.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<properties>
|
||||
<assertj-core.version>3.16.1</assertj-core.version>
|
||||
<commons-collections4.version>4.4</commons-collections4.version>
|
||||
<junit-jupiter.version>5.6.2</junit-jupiter.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.listassert;
|
||||
|
||||
import org.apache.commons.collections4.CollectionUtils;
|
||||
import org.hamcrest.MatcherAssert;
|
||||
import org.hamcrest.Matchers;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class OrderAgnosticListComparisonUnitTest {
|
||||
|
||||
private final List<Integer> first = Arrays.asList(1, 3, 4, 6, 8);
|
||||
private final List<Integer> second = Arrays.asList(8, 1, 6, 3, 4);
|
||||
private final List<Integer> third = Arrays.asList(1, 3, 3, 6, 6);
|
||||
|
||||
@Test
|
||||
public void whenTestingForOrderAgnosticEquality_ShouldBeTrue() {
|
||||
assertTrue(first.size() == second.size() && first.containsAll(second) && second.containsAll(first));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestingForOrderAgnosticEquality_ShouldBeFalse() {
|
||||
assertFalse(first.size() == third.size() && first.containsAll(third) && third.containsAll(first));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestingForOrderAgnosticEquality_ShouldBeEqual() {
|
||||
MatcherAssert.assertThat(first, Matchers.containsInAnyOrder(second.toArray()));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenTestingForOrderAgnosticEquality_ShouldBeTrueIfEqualOtherwiseFalse() {
|
||||
assertTrue(CollectionUtils.isEqualCollection(first, second));
|
||||
assertFalse(CollectionUtils.isEqualCollection(first, third));
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTestingForOrderAgnosticEqualityBothList_ShouldBeEqual() {
|
||||
assertThat(first).hasSameElementsAs(second);
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTestingForOrderAgnosticEqualityBothList_ShouldNotBeEqual() {
|
||||
List<String> a = Arrays.asList("a", "a", "b", "c");
|
||||
List<String> b = Arrays.asList("a", "b", "c");
|
||||
|
||||
assertThat(a).hasSameElementsAs(b);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
### Relevant Articles:
|
||||
|
||||
- [Guide to the System Rules Library](https://www.baeldung.com/java-system-rules-junit)
|
||||
- [Guide to the System Stubs Library](https://www.baeldung.com/java-system-stubs)
|
||||
@@ -0,0 +1,91 @@
|
||||
<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>testing-libraries-2</artifactId>
|
||||
<name>testing-libraries-2</name>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>testing-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.stefanbirkner</groupId>
|
||||
<artifactId>system-rules</artifactId>
|
||||
<version>${system-rules.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.stefanbirkner</groupId>
|
||||
<artifactId>system-lambda</artifactId>
|
||||
<version>${system-lambda.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>system-stubs-jupiter</artifactId>
|
||||
<version>${system-stubs.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>uk.org.webcompere</groupId>
|
||||
<artifactId>system-stubs-junit4</artifactId>
|
||||
<version>${system-stubs.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- System Stubs requires more up to date JUnit 5 -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-engine</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-params</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>${junit.jupiter.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<finalName>testing-libraries</finalName>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>src/test/resources</directory>
|
||||
<filtering>true</filtering>
|
||||
</resource>
|
||||
</resources>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<system-rules.version>1.19.0</system-rules.version>
|
||||
<system-lambda.version>1.0.0</system-lambda.version>
|
||||
<system-stubs.version>1.1.0</system-stubs.version>
|
||||
<junit.jupiter.version>5.6.2</junit.jupiter.version>
|
||||
<assertj-core.version>3.16.1</assertj-core.version>
|
||||
</properties>
|
||||
</project>
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import static org.junit.Assert.assertNull;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.contrib.java.lang.system.ClearSystemProperties;
|
||||
|
||||
public class ClearSystemPropertiesWithRuleUnitTest {
|
||||
|
||||
@Rule
|
||||
public final ClearSystemProperties userNameIsClearedRule = new ClearSystemProperties("user.name");
|
||||
|
||||
@Test
|
||||
public void givenClearUsernameProperty_whenGetUserName_thenNull() {
|
||||
assertNull(System.getProperty("user.name"));
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import static com.github.stefanbirkner.systemlambda.SystemLambda.restoreSystemProperties;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ProvidesSystemPropertyUnitTest {
|
||||
|
||||
@BeforeAll
|
||||
static void setUpBeforeClass() throws Exception {
|
||||
System.setProperty("log_dir", "/tmp/baeldung/logs");
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenSetSystemProperty_whenGetLogDir_thenLogDirIsProvidedSuccessfully() throws Exception {
|
||||
restoreSystemProperties(() -> {
|
||||
System.setProperty("log_dir", "test/resources");
|
||||
assertEquals("log_dir should be provided", "test/resources", System.getProperty("log_dir"));
|
||||
});
|
||||
|
||||
assertEquals("log_dir should be provided", "/tmp/baeldung/logs", System.getProperty("log_dir"));
|
||||
}
|
||||
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
|
||||
|
||||
public class ProvidesSystemPropertyWithRuleUnitTest {
|
||||
|
||||
@Rule
|
||||
public final ProvideSystemProperty providesSystemPropertyRule = new ProvideSystemProperty("log_dir", "test/resources").and("another_property", "another_value");
|
||||
|
||||
@Rule
|
||||
public final ProvideSystemProperty providesSystemPropertyFromFileRule = ProvideSystemProperty.fromResource("/test.properties");
|
||||
|
||||
@BeforeClass
|
||||
public static void setUpBeforeClass() {
|
||||
setLogs();
|
||||
}
|
||||
|
||||
@AfterClass
|
||||
public static void tearDownAfterClass() throws Exception {
|
||||
System.out.println(System.getProperty("log_dir"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProvideSystemProperty_whenGetLogDir_thenLogDirIsProvidedSuccessfully() {
|
||||
assertEquals("log_dir should be provided", "test/resources", System.getProperty("log_dir"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenProvideSystemPropertyFromFile_whenGetName_thenNameIsProvidedSuccessfully() {
|
||||
assertEquals("name should be provided", "baeldung", System.getProperty("name"));
|
||||
assertEquals("version should be provided", "1.0", System.getProperty("version"));
|
||||
}
|
||||
|
||||
private static void setLogs() {
|
||||
System.setProperty("log_dir", "/tmp/baeldung/logs");
|
||||
}
|
||||
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import static com.github.stefanbirkner.systemlambda.SystemLambda.tapSystemErr;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SystemErrPrintlnUnitTest {
|
||||
|
||||
@Test
|
||||
void givenTapSystemErr_whenInvokePrintln_thenOutputIsReturnedSuccessfully() throws Exception {
|
||||
|
||||
String text = tapSystemErr(() -> {
|
||||
printError("An error occurred Baeldung Readers!!");
|
||||
});
|
||||
|
||||
Assert.assertEquals("An error occurred Baeldung Readers!!", text.trim());
|
||||
}
|
||||
|
||||
private void printError(String output) {
|
||||
System.err.println(output);
|
||||
}
|
||||
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.contrib.java.lang.system.SystemErrRule;
|
||||
|
||||
public class SystemErrPrintlnWithRuleUnitTest {
|
||||
|
||||
@Rule
|
||||
public final SystemErrRule systemErrRule = new SystemErrRule().enableLog();
|
||||
|
||||
@Test
|
||||
public void givenSystemErrRule_whenInvokePrintln_thenLogSuccess() {
|
||||
printError("An Error occurred Baeldung Readers!!");
|
||||
|
||||
Assert.assertEquals("An Error occurred Baeldung Readers!!", systemErrRule.getLog()
|
||||
.trim());
|
||||
}
|
||||
|
||||
private void printError(String output) {
|
||||
System.err.println(output);
|
||||
}
|
||||
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import static com.github.stefanbirkner.systemlambda.SystemLambda.catchSystemExit;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SystemExitUnitTest {
|
||||
|
||||
@Test
|
||||
void givenCatchSystemExit_whenAppCallsSystemExit_thenStatusIsReturnedSuccessfully() throws Exception {
|
||||
int statusCode = catchSystemExit(() -> {
|
||||
exit();
|
||||
});
|
||||
assertEquals("status code should be 1:", 1, statusCode);
|
||||
}
|
||||
|
||||
private void exit() {
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.contrib.java.lang.system.ExpectedSystemExit;
|
||||
|
||||
public class SystemExitWithRuleUnitTest {
|
||||
|
||||
@Rule
|
||||
public final ExpectedSystemExit exitRule = ExpectedSystemExit.none();
|
||||
|
||||
@Test
|
||||
public void givenSystemExitRule_whenAppCallsSystemExit_thenExitRuleWorkssAsExpected() {
|
||||
exitRule.expectSystemExitWithStatus(1);
|
||||
exit();
|
||||
}
|
||||
|
||||
private void exit() {
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import static com.github.stefanbirkner.systemlambda.SystemLambda.withTextFromSystemIn;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class SystemInUnitTest {
|
||||
|
||||
@Test
|
||||
void givenTwoNames_whenSystemInMock_thenNamesJoinedTogether() throws Exception {
|
||||
withTextFromSystemIn("Jonathan", "Cook").execute(() -> {
|
||||
assertEquals("Names should be concatenated", "Jonathan Cook", getFullname());
|
||||
});
|
||||
}
|
||||
|
||||
private String getFullname() {
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
String firstName = scanner.next();
|
||||
String surname = scanner.next();
|
||||
return String.join(" ", firstName, surname);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.systemrules;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
|
||||
import static org.junit.contrib.java.lang.system.TextFromStandardInputStream.emptyStandardInputStream;
|
||||
|
||||
public class SystemInWithRuleUnitTest {
|
||||
|
||||
@Rule
|
||||
public final TextFromStandardInputStream systemInMock = emptyStandardInputStream();
|
||||
|
||||
@Test
|
||||
public void givenTwoNames_whenSystemInMock_thenNamesJoinedTogether() {
|
||||
systemInMock.provideLines("Jonathan", "Cook");
|
||||
assertEquals("Names should be concatenated", "Jonathan Cook", getFullname());
|
||||
}
|
||||
|
||||
private String getFullname() {
|
||||
try (Scanner scanner = new Scanner(System.in)) {
|
||||
String firstName = scanner.next();
|
||||
String surname = scanner.next();
|
||||
return String.join(" ", firstName, surname);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user