BAEL-3335 example of reading request multiple times. removed spring boot and using spring-webmvc

This commit is contained in:
sumit-bhawsar
2019-10-20 04:01:29 +01:00
parent db85c8f275
commit 2e97ec17f4
20450 changed files with 1641014 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
### Relevant Articles
- [Guide to JUnit 4 Rules](https://www.baeldung.com/junit-4-rules)
- [Custom JUnit 4 Test Runners](http://www.baeldung.com/junit-4-custom-runners)
- [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)
+31
View File
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>junit-4</artifactId>
<version>1.0-SNAPSHOT</version>
<name>junit-4</name>
<description>JUnit 4 Topics</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>${jUnitParams.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<jUnitParams.version>1.1.0</jUnitParams.version>
</properties>
</project>
@@ -0,0 +1,11 @@
package com.baeldung.junit;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
}
@@ -0,0 +1,15 @@
package com.baeldung.junitparams;
public class SafeAdditionUtil {
public int safeAdd(int a, int b) {
long result = ((long) a) + b;
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) result;
}
}
@@ -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>
@@ -0,0 +1,14 @@
package com.baeldung.junit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AdditionUnitTest {
Calculator calculator = new Calculator();
@Test
public void testAddition() {
assertEquals("addition", 8, calculator.add(5, 3));
}
}
@@ -0,0 +1,18 @@
package com.baeldung.junit;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
public class BlockingTestRunner extends BlockJUnit4ClassRunner {
public BlockingTestRunner(Class<?> klass) throws InitializationError {
super(klass);
}
@Override
protected Statement methodInvoker(FrameworkMethod method, Object test) {
System.out.println("invoking: " + method.getName());
return super.methodInvoker(method, test);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.junit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import static org.junit.Assert.assertEquals;
@RunWith(JUnit4.class)
public class CalculatorUnitTest {
Calculator calculator = new Calculator();
@Test
public void testAddition() {
assertEquals("addition", 8, calculator.add(5, 3));
}
}
@@ -0,0 +1,14 @@
package com.baeldung.junit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class SubstractionUnitTest {
Calculator calculator = new Calculator();
@Test
public void substraction() {
assertEquals("substraction", 2, calculator.sub(5, 3));
}
}
@@ -0,0 +1,12 @@
package com.baeldung.junit;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({
AdditionUnitTest.class,
SubstractionUnitTest.class})
public class SuiteUnitTest {
}
@@ -0,0 +1,41 @@
package com.baeldung.junit;
import org.junit.Test;
import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import java.lang.reflect.Method;
public class TestRunner extends Runner {
private Class testClass;
public TestRunner(Class testClass) {
super();
this.testClass = testClass;
}
@Override
public Description getDescription() {
return Description.createTestDescription(testClass, "My runner description");
}
@Override
public void run(RunNotifier notifier) {
System.out.println("running the tests from MyRunner: " + testClass);
try {
Object testObject = testClass.newInstance();
for (Method method : testClass.getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
notifier.fireTestStarted(Description
.createTestDescription(testClass, method.getName()));
method.invoke(testObject);
notifier.fireTestFinished(Description
.createTestDescription(testClass, method.getName()));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
@@ -0,0 +1,54 @@
package com.baeldung.junitparams;
import junitparams.FileParameters;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(JUnitParamsRunner.class)
public class SafeAdditionUtilUnitTest {
private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil();
@Test
@Parameters({"1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15"})
public void whenWithAnnotationProvidedParams_thenSafeAdd(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@Test
@Parameters(method = "parametersToTestAdd")
public void whenWithNamedMethod_thendSafeAdd(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
private Object[] parametersToTestAdd() {
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}};
}
@Test
@Parameters
public void whenWithnoParam_thenLoadByNameSafeAdd(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
private Object[] parametersForWhenWithnoParam_thenLoadByNameSafeAdd() {
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -8, Integer.MIN_VALUE}};
}
@Test
@Parameters(source = TestDataProvider.class)
public void whenWithNamedClass_thenSafeAdd(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@Test
@FileParameters("src/test/resources/JunitParamsTestParameters.csv")
public void whenWithCsvFile_thenSafeAdd(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
}
@@ -0,0 +1,13 @@
package com.baeldung.junitparams;
public class TestDataProvider {
public static Object[] provideBasicData() {
return new Object[]{new Object[]{1, 2, 3}, new Object[]{-10, 30, 20}, new Object[]{15, -5, 10}, new Object[]{-5, -10, -15}};
}
public static Object[] provideEdgeCaseData() {
return new Object[]{new Object[]{Integer.MAX_VALUE, 2, Integer.MAX_VALUE}, new Object[]{Integer.MIN_VALUE, -2, Integer.MIN_VALUE},};
}
}
@@ -0,0 +1,34 @@
package com.baeldung.rules;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MessageLogger implements TestRule {
private static final Logger LOG = LoggerFactory.getLogger(MessageLogger.class);
private String message;
public MessageLogger(String message) {
this.message = message;
}
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
try {
LOG.info("Starting: {}", message);
base.evaluate();
} finally {
LOG.info("Finished: {}", message);
}
}
};
}
}
@@ -0,0 +1,21 @@
package com.baeldung.rules;
import static org.junit.Assert.assertTrue;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
public class RuleChainUnitTest {
@Rule
public RuleChain chain = RuleChain.outerRule(new MessageLogger("First rule"))
.around(new MessageLogger("Second rule"))
.around(new MessageLogger("Third rule"));
@Test
public void givenRuleChain_whenTestRuns_thenChainOrderApplied() {
assertTrue(true);
}
}
@@ -0,0 +1,88 @@
package com.baeldung.rules;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.isA;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.ErrorCollector;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestName;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RulesUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(RulesUnitTest.class);
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Rule
public final ExpectedException thrown = ExpectedException.none();
@Rule
public TestName name = new TestName();
@Rule
public Timeout globalTimeout = Timeout.seconds(10);
@Rule
public final ErrorCollector errorCollector = new ErrorCollector();
@Rule
public DisableOnDebug disableTimeout = new DisableOnDebug(Timeout.seconds(30));
@Rule
public TestMethodNameLogger testLogger = new TestMethodNameLogger();
@Test
public void givenTempFolderRule_whenNewFile_thenFileIsCreated() throws IOException {
File testFile = tmpFolder.newFile("test-file.txt");
assertTrue("The file should have been created: ", testFile.isFile());
assertEquals("Temp folder and test file should match: ", tmpFolder.getRoot(), testFile.getParentFile());
}
@Test
public void givenIllegalArgument_whenExceptionThrown_thenMessageAndCauseMatches() {
thrown.expect(IllegalArgumentException.class);
thrown.expectCause(isA(NullPointerException.class));
thrown.expectMessage("This is illegal");
throw new IllegalArgumentException("This is illegal", new NullPointerException());
}
@Test
public void givenAddition_whenPrintingTestName_thenTestNameIsDisplayed() {
LOG.info("Executing: {}", name.getMethodName());
assertEquals("givenAddition_whenPrintingTestName_thenTestNameIsDisplayed", name.getMethodName());
}
@Ignore
@Test
public void givenLongRunningTest_whenTimout_thenTestFails() throws InterruptedException {
TimeUnit.SECONDS.sleep(20);
}
@Ignore
@Test
public void givenMultipleErrors_whenTestRuns_thenCollectorReportsErrors() {
errorCollector.addError(new Throwable("First thing went wrong!"));
errorCollector.addError(new Throwable("Another thing went wrong!"));
errorCollector.checkThat("Hello World", not(containsString("ERROR!")));
}
}
@@ -0,0 +1,32 @@
package com.baeldung.rules;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestMethodNameLogger implements TestRule {
private static final Logger LOG = LoggerFactory.getLogger(TestMethodNameLogger.class);
@Override
public Statement apply(Statement base, Description description) {
logInfo("Before test", description);
try {
return new Statement() {
@Override
public void evaluate() throws Throwable {
base.evaluate();
}
};
} finally {
logInfo("After test", description);
}
}
private void logInfo(String msg, Description description) {
LOG.info(msg + description.getMethodName());
}
}
@@ -0,0 +1,30 @@
package com.baeldung.rules;
import static org.junit.Assert.assertFalse;
import java.util.ArrayList;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Verifier;
public class VerifierRuleUnitTest {
private List<String> messageLog = new ArrayList<String>();
@Rule
public Verifier verifier = new Verifier() {
@Override
public void verify() {
assertFalse("Message Log is not Empty!", messageLog.isEmpty());
}
};
@Test
public void givenNewMessage_whenVerified_thenMessageLogNotEmpty() {
// ...
messageLog.add("There is a new message!");
}
}
@@ -0,0 +1,24 @@
package com.baeldung.runfromjava;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class FirstUnitTest {
@Test
public void whenThis_thenThat() {
assertTrue(true);
}
@Test
public void whenSomething_thenSomething() {
assertTrue(true);
}
@Test
public void whenSomethingElse_thenSomethingElse() {
assertTrue(true);
}
}
@@ -0,0 +1,10 @@
package com.baeldung.runfromjava;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({ FirstUnitTest.class, SecondUnitTest.class })
public class MyTestSuite {
}
@@ -0,0 +1,93 @@
package com.baeldung.runfromjava;
import junit.extensions.ActiveTestSuite;
import junit.extensions.RepeatedTest;
import junit.framework.JUnit4TestAdapter;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.internal.TextListener;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class RunJUnit4TestsFromJava {
public static void runOne() {
JUnitCore junit = new JUnitCore();
junit.addListener(new TextListener(System.out));
junit.run(FirstUnitTest.class);
}
public static void runAllClasses() {
JUnitCore junit = new JUnitCore();
junit.addListener(new TextListener(System.out));
Result result = junit.run(FirstUnitTest.class, SecondUnitTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
resultReport(result);
}
public static void runSuiteOfClasses() {
JUnitCore junit = new JUnitCore();
junit.addListener(new TextListener(System.out));
Result result = junit.run(MyTestSuite.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
resultReport(result);
}
public static void runRepeated() {
Test test = new JUnit4TestAdapter(SecondUnitTest.class);
RepeatedTest repeatedTest = new RepeatedTest(test, 5);
JUnitCore junit = new JUnitCore();
junit.addListener(new TextListener(System.out));
junit.run(repeatedTest);
}
public static void runRepeatedSuite() {
TestSuite mySuite = new ActiveTestSuite();
JUnitCore junit = new JUnitCore();
junit.addListener(new TextListener(System.out));
mySuite.addTest(new RepeatedTest(new JUnit4TestAdapter(FirstUnitTest.class), 5));
mySuite.addTest(new RepeatedTest(new JUnit4TestAdapter(SecondUnitTest.class), 3));
junit.run(mySuite);
}
public static void resultReport(Result result) {
System.out.println("Finished. Result: Failures: " +
result.getFailureCount() + ". Ignored: " +
result.getIgnoreCount() + ". Tests run: " +
result.getRunCount() + ". Time: " +
result.getRunTime() + "ms.");
}
public static void main(String[] args) {
System.out.println("\nRunning one test class:");
runOne();
System.out.println("\nRunning all test classes:");
runAllClasses();
System.out.println("\nRunning a suite of test classes:");
runSuiteOfClasses();
System.out.println("\nRunning repeated tests:");
runRepeated();
System.out.println("\nRunning repeated suite tests:");
runRepeatedSuite();
}
}
@@ -0,0 +1,18 @@
package com.baeldung.runfromjava;
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class SecondUnitTest {
@Test
public void whenSomething_thenSomething() {
assertTrue(true);
}
@Test
public void whensomethingElse_thenSomethingElse() {
assertTrue(true);
}
}
@@ -0,0 +1,4 @@
1,2,3
-10, 30, 20
15, -5, 10
-5, -10, -15
1 1 2 3
2 -10 30 20
3 15 -5 10
4 -5 -10 -15