JAVA-8405: reducing logging for tutorials-build-job

This commit is contained in:
chaos2418 2021-11-18 11:19:23 +05:30
parent 157d7ee61c
commit 58e6087b3d
81 changed files with 715 additions and 126 deletions

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,15 +1,20 @@
package com.baeldung.java8.lambda.exceptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.function.Consumer;
public class LambdaExceptionWrappers {
private static final Logger LOGGER = LoggerFactory.getLogger(LambdaExceptionWrappers.class);
public static Consumer<Integer> lambdaWrapper(Consumer<Integer> consumer) {
return i -> {
try {
consumer.accept(i);
} catch (ArithmeticException e) {
System.err.println("Arithmetic Exception occured : " + e.getMessage());
LOGGER.error("Arithmetic Exception occured : {}", e.getMessage());
}
};
}
@ -21,7 +26,7 @@ public class LambdaExceptionWrappers {
} catch (Exception ex) {
try {
E exCast = clazz.cast(ex);
System.err.println("Exception occured : " + exCast.getMessage());
LOGGER.error("Exception occured : {}", exCast.getMessage());
} catch (ClassCastException ccEx) {
throw ex;
}
@ -46,7 +51,7 @@ public class LambdaExceptionWrappers {
} catch (Exception ex) {
try {
E exCast = exceptionClass.cast(ex);
System.err.println("Exception occured : " + exCast.getMessage());
LOGGER.error("Exception occured : {}", exCast.getMessage());
} catch (ClassCastException ccEx) {
throw new RuntimeException(ex);
}

View File

@ -7,14 +7,16 @@ import java.util.function.BiFunction;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MethodReferenceUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodReferenceUnitTest.class);
private static <T> void doNothingAtAll(Object... o) {
}
;
@Test
public void referenceToStaticMethod() {
List<String> messages = Arrays.asList("Hello", "Baeldung", "readers!");
@ -61,7 +63,7 @@ public class MethodReferenceUnitTest {
@Test
public void limitationsAndAdditionalExamples() {
createBicyclesList().forEach(b -> System.out.printf("Bike brand is '%s' and frame size is '%d'%n", b.getBrand(), b.getFrameSize()));
createBicyclesList().forEach(b -> LOGGER.debug("Bike brand is '{}' and frame size is '{}'", b.getBrand(), b.getFrameSize()));
createBicyclesList().forEach((o) -> MethodReferenceUnitTest.doNothingAtAll(o));
}

View File

@ -7,6 +7,6 @@ public class Building {
private static final Logger LOGGER = LoggerFactory.getLogger(Building.class);
public void paint() {
LOGGER.info("Painting Building");
LOGGER.debug("Painting Building");
}
}

View File

@ -7,6 +7,6 @@ public class House extends Building {
private static final Logger LOGGER = LoggerFactory.getLogger(House.class);
public void paint() {
LOGGER.info("Painting House");
LOGGER.debug("Painting House");
}
}

View File

@ -1,8 +1,13 @@
package com.baeldung.initializationguide;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
public class User implements Serializable, Cloneable {
private static final Logger LOGGER = LoggerFactory.getLogger(User.class);
private static final long serialVersionUID = 1L;
static String forum;
private String name;
@ -10,12 +15,12 @@ public class User implements Serializable, Cloneable {
{
id = 0;
System.out.println("Instance Initializer");
LOGGER.debug("Instance Initializer");
}
static {
forum = "Java";
System.out.println("Static Initializer");
forum = "Java";
LOGGER.debug("Static Initializer");
}
public User(String name, int id) {
@ -25,7 +30,7 @@ public class User implements Serializable, Cloneable {
}
public User() {
System.out.println("Constructor");
LOGGER.debug("Constructor");
}
public String getName() {

View File

@ -1,12 +1,17 @@
package com.baeldung.loops;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoopsInJava {
private static final Logger LOGGER = LoggerFactory.getLogger(LoopsInJava.class);
public int[] simple_for_loop() {
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {
arr[i] = i;
System.out.println("Simple for loop: i - " + i);
LOGGER.debug("Simple for loop: i - " + i);
}
return arr;
}
@ -16,7 +21,7 @@ public class LoopsInJava {
int[] arr = new int[5];
for (int num : intArr) {
arr[num] = num;
System.out.println("Enhanced for-each loop: i - " + num);
LOGGER.debug("Enhanced for-each loop: i - " + num);
}
return arr;
}
@ -26,7 +31,7 @@ public class LoopsInJava {
int[] arr = new int[5];
while (i < 5) {
arr[i] = i;
System.out.println("While loop: i - " + i++);
LOGGER.debug("While loop: i - " + i++);
}
return arr;
}
@ -36,7 +41,7 @@ public class LoopsInJava {
int[] arr = new int[5];
do {
arr[i] = i;
System.out.println("Do-While loop: i - " + i++);
LOGGER.debug("Do-While loop: i - " + i++);
} while (i < 5);
return arr;
}

View File

@ -1,7 +1,13 @@
package com.baeldung.switchstatement;
import com.baeldung.loops.LoopsInJava;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SwitchStatement {
private static final Logger LOGGER = LoggerFactory.getLogger(SwitchStatement.class);
public String exampleOfIF(String animal) {
String result;
@ -42,11 +48,11 @@ public class SwitchStatement {
switch (animal) {
case "DOG":
System.out.println("domestic animal");
LOGGER.debug("domestic animal");
result = "domestic animal";
default:
System.out.println("unknown animal");
LOGGER.debug("unknown animal");
result = "unknown animal";
}

View File

@ -8,12 +8,16 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.baeldung.initializationguide.User;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LoopsUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(LoopsUnitTest.class);
private LoopsInJava loops = new LoopsInJava();
private static List<String> list = new ArrayList<>();
private static Set<String> set = new HashSet<>();
@ -65,41 +69,44 @@ public class LoopsUnitTest {
@Test
public void whenUsingSimpleFor_shouldIterateList() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
LOGGER.debug(list.get(i));
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateList() {
for (String item : list) {
System.out.println(item);
LOGGER.debug(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateSet() {
for (String item : set) {
System.out.println(item);
LOGGER.debug(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateMap() {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
LOGGER.debug("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
}
}
@Test
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
aa: for (int i = 1; i <= 3; i++) {
if (i == 1)
aa:
for (int i = 1; i <= 3; i++) {
if (i == 1) {
continue;
bb: for (int j = 1; j <= 3; j++) {
}
bb:
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break aa;
}
System.out.println(i + " " + j);
LOGGER.debug(i + " " + j);
}
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

12
logback-config.xml Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -24,7 +24,7 @@ public class HibernateUtil {
settings.put(Environment.USER, "sa");
settings.put(Environment.PASS, "");
settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.SHOW_SQL, "false");
settings.put(Environment.HBM2DDL_AUTO, "update");
configuration.setProperties(settings);
configuration.addAnnotatedClass(User.class);

View File

@ -27,7 +27,7 @@ public class HibernateUtil {
settings.put(Environment.USER, "sa");
settings.put(Environment.PASS, "");
settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.SHOW_SQL, "false");
settings.put(Environment.USE_SQL_COMMENTS, "true");
settings.put(Environment.HBM2DDL_AUTO, "update");
configuration.setProperties(settings);

View File

@ -16,7 +16,7 @@ public class CustomInterceptor extends EmptyInterceptor {
@Override
public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
if (entity instanceof User) {
logger.info(((User) entity).toString());
logger.debug(entity.toString());
}
return super.onSave(entity, id, state, propertyNames, types);
}
@ -25,7 +25,7 @@ public class CustomInterceptor extends EmptyInterceptor {
public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object [] previousState, String[] propertyNames, Type[] types) {
if (entity instanceof User) {
((User) entity).setLastModified(new Date());
logger.info(((User) entity).toString());
logger.debug(entity.toString());
}
return super.onFlushDirty(entity, id, currentState, previousState, propertyNames, types);
}

View File

@ -1,7 +1,5 @@
package com.baeldung.hibernate.interceptors.entity;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
@ -9,6 +7,7 @@ import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Date;
@Entity(name = "hbi_user")
public class User {

View File

@ -42,9 +42,9 @@ public class HibernateHiloUnitTest {
private void configureLogger() {
BasicConfigurator.configure();
LogManager.getLogger("org.hibernate").setLevel(Level.ERROR);
LogManager.getLogger("org.hibernate.id.enhanced.SequenceStructure").setLevel(Level.DEBUG);
LogManager.getLogger("org.hibernate.event.internal.AbstractSaveEventListener").setLevel(Level.DEBUG);
LogManager.getLogger("org.hibernate.SQL").setLevel(Level.DEBUG);
LogManager.getLogger("org.hibernate.id.enhanced.SequenceStructure").setLevel(Level.INFO);
LogManager.getLogger("org.hibernate.event.internal.AbstractSaveEventListener").setLevel(Level.INFO);
LogManager.getLogger("org.hibernate.SQL").setLevel(Level.INFO);
}

View File

@ -1,5 +1,8 @@
package com.baeldung.hibernate.proxy;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.hibernate.*;
import org.hibernate.proxy.HibernateProxy;
import org.junit.After;

View File

@ -2,7 +2,7 @@ hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:hilo_db;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20

View File

@ -5,6 +5,6 @@ hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.current_session_context_class=org.hibernate.context.internal.ThreadLocalSessionContext

View File

@ -5,5 +5,5 @@ hibernate.connection.password=
hibernate.connection.autocommit=true
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.show_sql=false
hibernate.hbm2ddl.auto=validate

View File

@ -3,7 +3,7 @@ hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy

View File

@ -3,5 +3,5 @@ hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop

View File

@ -5,7 +5,7 @@ hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.c3p0.min_size=5

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -3,12 +3,14 @@ package com.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.boot.Application;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@TestPropertySource(properties = {"spring.jpa.show-sql=false "})
public class SpringContextTest {
@Test

View File

@ -7,6 +7,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.partialupdate.model.Customer;
@ -16,6 +17,7 @@ import com.baeldung.partialupdate.service.CustomerService;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = PartialUpdateApplication.class)
@TestPropertySource(properties = {"spring.jpa.show-sql=false "})
public class PartialUpdateUnitTest {
@Autowired

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
<logger name="org.hibernate" level="INFO"/>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -289,7 +289,6 @@
<id>default-first</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
@ -309,6 +308,9 @@
<exclude>**/JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<logback.configurationFile>${tutorialsproject.basedir}/logback-config.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>
@ -576,6 +578,9 @@
<exclude>**/*JdbcTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<systemPropertyVariables>
<logback.configurationFile>${tutorialsproject.basedir}/logback-config.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,21 +1,25 @@
package com.baeldung.backpressure;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.BaseSubscriber;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
public class BackpressureUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(BackpressureUnitTest.class);
@Test
public void whenLimitRateSet_thenSplitIntoChunks() throws InterruptedException {
Flux<Integer> limit = Flux.range(1, 25);
limit.limitRate(10);
limit.subscribe(
value -> System.out.println(value),
value -> LOGGER.debug(String.valueOf(value)),
err -> err.printStackTrace(),
() -> System.out.println("Finished!!"),
() -> LOGGER.debug("Finished!!"),
subscription -> subscription.request(15)
);
@ -34,12 +38,12 @@ public class BackpressureUnitTest {
Flux<Integer> request = Flux.range(1, 50);
request.subscribe(
System.out::println,
integer -> LOGGER.debug(String.valueOf(integer)),
err -> err.printStackTrace(),
() -> System.out.println("All 50 items have been successfully processed!!!"),
() -> LOGGER.debug("All 50 items have been successfully processed!!!"),
subscription -> {
for (int i = 0; i < 5; i++) {
System.out.println("Requesting the next 10 elements!!!");
LOGGER.debug("Requesting the next 10 elements!!!");
subscription.request(10);
}
}
@ -68,7 +72,7 @@ public class BackpressureUnitTest {
@Override
protected void hookOnNext(Integer value) {
request(3);
System.out.println(value);
LOGGER.debug(String.valueOf(value));
cancel();
}
});

View File

@ -65,6 +65,15 @@
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<logback.configurationFile>${project.basedir}/src/main/resources/logback.xml</logback.configurationFile>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,8 +1,12 @@
package com.baeldung.ehcache.calculator;
import com.baeldung.ehcache.config.CacheHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SquaredCalculator {
private static final Logger LOGGER = LoggerFactory.getLogger(SquaredCalculator.class);
private CacheHelper cache;
public int getSquareValueOfNumber(int input) {
@ -10,7 +14,7 @@ public class SquaredCalculator {
return cache.getSquareNumberCache().get(input);
}
System.out.println("Calculating square value of " + input + " and caching result.");
LOGGER.debug("Calculating square value of {} and caching result.", input);
int squaredValue = (int) Math.pow(input, 2);
cache.getSquareNumberCache().put(input, squaredValue);

View File

@ -4,13 +4,18 @@ import com.baeldung.ehcache.calculator.SquaredCalculator;
import com.baeldung.ehcache.config.CacheHelper;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SquareCalculatorUnitTest {
private SquaredCalculator squaredCalculator = new SquaredCalculator();
private CacheHelper cacheHelper = new CacheHelper();
private static final Logger LOGGER = LoggerFactory.getLogger(SquareCalculatorUnitTest.class);
private final SquaredCalculator squaredCalculator = new SquaredCalculator();
private final CacheHelper cacheHelper = new CacheHelper();
@Before
public void setup() {
@ -20,21 +25,24 @@ public class SquareCalculatorUnitTest {
@Test
public void whenCalculatingSquareValueOnce_thenCacheDontHaveValues() {
for (int i = 10; i < 15; i++) {
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n");
assertFalse(cacheHelper.getSquareNumberCache()
.containsKey(i));
LOGGER.debug("Square value of {} is: {}", i, squaredCalculator.getSquareValueOfNumber(i));
}
}
@Test
public void whenCalculatingSquareValueAgain_thenCacheHasAllValues() {
for (int i = 10; i < 15; i++) {
assertFalse(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n");
assertFalse(cacheHelper.getSquareNumberCache()
.containsKey(i));
LOGGER.debug("Square value of {} is: {}", i, squaredCalculator.getSquareValueOfNumber(i));
}
for (int i = 10; i < 15; i++) {
assertTrue(cacheHelper.getSquareNumberCache().containsKey(i));
System.out.println("Square value of " + i + " is: " + squaredCalculator.getSquareValueOfNumber(i) + "\n");
assertTrue(cacheHelper.getSquareNumberCache()
.containsKey(i));
LOGGER.debug("Square value of {} is: {}", i, squaredCalculator.getSquareValueOfNumber(i) + "\n");
}
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="15 seconds" debug="false">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{ISO8601}]-[%thread] %-5level %logger - %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -23,19 +23,19 @@ public class BeforeAndAfterAnnotationsUnitTest {
@Before
public void init() {
LOG.info("startup");
LOG.debug("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
@After
public void teardown() {
LOG.info("teardown");
LOG.debug("teardown");
list.clear();
}
@Test
public void whenCheckingListSize_thenSizeEqualsToInit() {
LOG.info("executing test");
LOG.debug("executing test");
assertEquals(2, list.size());
list.add("another test");
@ -43,7 +43,7 @@ public class BeforeAndAfterAnnotationsUnitTest {
@Test
public void whenCheckingListSizeAgain_thenSizeEqualsToInit() {
LOG.info("executing another test");
LOG.debug("executing another test");
assertEquals(2, list.size());
list.add("yet another test");

View File

@ -12,24 +12,24 @@ import org.slf4j.LoggerFactory;
public class BeforeClassAndAfterClassAnnotationsUnitTest {
private static final Logger LOG = LoggerFactory.getLogger(BeforeClassAndAfterClassAnnotationsUnitTest.class);
@BeforeClass
public static void setup() {
LOG.info("startup - creating DB connection");
LOG.debug("startup - creating DB connection");
}
@AfterClass
public static void tearDown() {
LOG.info("closing DB connection");
LOG.debug("closing DB connection");
}
@Test
public void simpleTest() {
LOG.info("simple test");
LOG.debug("simple test");
}
@Test
public void anotherSimpleTest() {
LOG.info("another simple test");
LOG.debug("another simple test");
}
}

View File

@ -1,18 +1,21 @@
package com.baeldung.migration.junit4;
import com.baeldung.migration.junit4.rules.TraceUnitTestRule;
import org.junit.Rule;
import org.junit.Test;
import com.baeldung.migration.junit4.rules.TraceUnitTestRule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RuleExampleUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RuleExampleUnitTest.class);
@Rule
public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule();
@Test
public void whenTracingTests() {
System.out.println("This is my test");
LOGGER.debug("This is my test");
/*...*/
}
}

View File

@ -1,15 +1,19 @@
package com.baeldung.migration.junit4.rules;
import java.util.ArrayList;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
public class TraceUnitTestRule implements TestRule {
private static final Logger LOGGER = LoggerFactory.getLogger(TraceUnitTestRule.class);
@Override
public Statement apply(Statement base, Description description) {
@ -18,13 +22,13 @@ public class TraceUnitTestRule implements TestRule {
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
System.out.println("Starting test ... " + description.getMethodName());
LOGGER.debug("Starting test ... {}", description.getMethodName());
try {
base.evaluate();
} catch (Throwable e) {
errors.add(e);
} finally {
System.out.println("... test finished. " + description.getMethodName());
LOGGER.debug("... test finished. {}", description.getMethodName());
}
MultipleFailureException.assertEmpty(errors);

View File

@ -15,21 +15,21 @@ public class BeforeAllAndAfterAllAnnotationsUnitTest {
@BeforeAll
public static void setup() {
LOG.info("startup - creating DB connection");
LOG.debug("startup - creating DB connection");
}
@AfterAll
public static void tearDown() {
LOG.info("closing DB connection");
LOG.debug("closing DB connection");
}
@Test
public void simpleTest() {
LOG.info("simple test");
LOG.debug("simple test");
}
@Test
public void anotherSimpleTest() {
LOG.info("another simple test");
LOG.debug("another simple test");
}
}

View File

@ -23,19 +23,19 @@ public class BeforeEachAndAfterEachAnnotationsUnitTest {
@BeforeEach
public void init() {
LOG.info("startup");
LOG.debug("startup");
list = new ArrayList<>(Arrays.asList("test1", "test2"));
}
@AfterEach
public void teardown() {
LOG.info("teardown");
LOG.debug("teardown");
list.clear();
}
@Test
public void whenCheckingListSize_ThenSizeEqualsToInit() {
LOG.info("executing test");
LOG.debug("executing test");
assertEquals(2, list.size());
list.add("another test");
@ -43,7 +43,7 @@ public class BeforeEachAndAfterEachAnnotationsUnitTest {
@Test
public void whenCheckingListSizeAgain_ThenSizeEqualsToInit() {
LOG.info("executing another test");
LOG.debug("executing another test");
assertEquals(2, list.size());
list.add("yet another test");

View File

@ -1,19 +1,22 @@
package com.baeldung.migration.junit5;
import com.baeldung.migration.junit5.extensions.TraceUnitExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import com.baeldung.migration.junit5.extensions.TraceUnitExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RunWith(JUnitPlatform.class)
@ExtendWith(TraceUnitExtension.class)
public class RuleExampleUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RuleExampleUnitTest.class);
@Test
public void whenTracingTests() {
System.out.println("This is my test");
LOGGER.debug("This is my test");
/*...*/
}
}

View File

@ -3,17 +3,21 @@ package com.baeldung.migration.junit5.extensions;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback {
private static final Logger LOGGER = LoggerFactory.getLogger(TraceUnitExtension.class);
@Override
public void beforeEach(ExtensionContext context) throws Exception {
System.out.println("Starting test ... " + context.getDisplayName());
LOGGER.debug("Starting test ... {}", context.getDisplayName());
}
@Override
public void afterEach(ExtensionContext context) throws Exception {
System.out.println("... test finished. " + context.getDisplayName());
LOGGER.debug("... test finished. {}", context.getDisplayName());
}
}

View File

@ -1,7 +1,10 @@
package com.baeldung.resourcedirectory;
import com.baeldung.migration.junit5.extensions.TraceUnitExtension;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.file.Path;
@ -9,6 +12,8 @@ import java.nio.file.Paths;
public class ReadResourceDirectoryUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(TraceUnitExtension.class);
@Test
public void givenResourcePath_whenReadAbsolutePathWithFile_thenAbsolutePathEndsWithDirectory() {
String path = "src/test/resources";
@ -16,7 +21,7 @@ public class ReadResourceDirectoryUnitTest {
File file = new File(path);
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);
LOGGER.debug(absolutePath);
Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources"));
}
@ -26,7 +31,7 @@ public class ReadResourceDirectoryUnitTest {
String absolutePath = resourceDirectory.toFile().getAbsolutePath();
System.out.println(absolutePath);
LOGGER.debug(absolutePath);
Assert.assertTrue(absolutePath.endsWith("src" + File.separator + "test" + File.separator + "resources"));
}
@ -38,7 +43,7 @@ public class ReadResourceDirectoryUnitTest {
File file = new File(classLoader.getResource(resourceName).getFile());
String absolutePath = file.getAbsolutePath();
System.out.println(absolutePath);
LOGGER.debug(absolutePath);
Assert.assertTrue(absolutePath.endsWith(File.separator + "example_resource.txt"));
}

View File

@ -20,12 +20,12 @@ public class RegisterExtensionSampleExtension implements BeforeAllCallback, Befo
@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
logger.info("Type {} In beforeAll : {}", type, extensionContext.getDisplayName());
logger.debug("Type {} In beforeAll : {}", type, extensionContext.getDisplayName());
}
@Override
public void beforeEach(ExtensionContext extensionContext) throws Exception {
logger.info("Type {} In beforeEach : {}", type, extensionContext.getDisplayName());
logger.debug("Type {} In beforeEach : {}", type, extensionContext.getDisplayName());
}
public String getType() {

View File

@ -1,41 +1,45 @@
package com.baeldung.junit5;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;
import org.junit.jupiter.api.TestInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class RepeatedTestAnnotationUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RepeatedTestAnnotationUnitTest.class);
@BeforeEach
void beforeEachTest() {
System.out.println("Before Each Test");
LOGGER.debug("Before Each Test");
}
@AfterEach
void afterEachTest() {
System.out.println("After Each Test");
System.out.println("=====================");
LOGGER.debug("After Each Test");
LOGGER.debug("=====================");
}
@RepeatedTest(3)
void repeatedTest(TestInfo testInfo) {
System.out.println("Executing repeated test");
LOGGER.debug("Executing repeated test");
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
}
@RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)
void repeatedTestWithLongName() {
System.out.println("Executing repeated test with long name");
LOGGER.debug("Executing repeated test with long name");
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
}
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
void repeatedTestWithShortName() {
System.out.println("Executing repeated test with long name");
LOGGER.debug("Executing repeated test with long name");
assertEquals(2, Math.addExact(1, 1), "1 + 1 should equal 2");
}
@ -46,7 +50,7 @@ public class RepeatedTestAnnotationUnitTest {
@RepeatedTest(3)
void repeatedTestWithRepetitionInfo(RepetitionInfo repetitionInfo) {
System.out.println("Repetition #" + repetitionInfo.getCurrentRepetition());
LOGGER.debug("Repetition # {}", repetitionInfo.getCurrentRepetition());
assertEquals(3, repetitionInfo.getTotalRepetitions());
}
}

View File

@ -2,7 +2,20 @@ package com.baeldung.junit5.conditional;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.*;
import org.junit.jupiter.api.condition.DisabledForJreRange;
import org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.DisabledIfSystemProperty;
import org.junit.jupiter.api.condition.DisabledOnJre;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
import org.junit.jupiter.api.condition.EnabledOnJre;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.JRE;
import org.junit.jupiter.api.condition.OS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@ -11,64 +24,66 @@ import java.lang.annotation.Target;
public class ConditionalAnnotationsUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ConditionalAnnotationsUnitTest.class);
@Test
@EnabledOnOs({OS.WINDOWS, OS.MAC})
public void shouldRunBothWindowsAndMac() {
System.out.println("runs on Windows and Mac");
LOGGER.debug("runs on Windows and Mac");
}
@Test
@DisabledOnOs(OS.LINUX)
public void shouldNotRunAtLinux() {
System.out.println("will not run on Linux");
LOGGER.debug("will not run on Linux");
}
@Test
@EnabledOnJre({JRE.JAVA_10, JRE.JAVA_11})
public void shouldOnlyRunOnJava10And11() {
System.out.println("runs with java 10 and 11");
LOGGER.debug("runs with java 10 and 11");
}
@Test
@EnabledForJreRange(min = JRE.JAVA_8, max = JRE.JAVA_13)
public void shouldOnlyRunOnJava8UntilJava13() {
System.out.println("runs with Java 8, 9, 10, 11, 12 and 13!");
LOGGER.debug("runs with Java 8, 9, 10, 11, 12 and 13!");
}
@Test
@DisabledForJreRange(min = JRE.JAVA_14, max = JRE.JAVA_15)
public void shouldNotBeRunOnJava14AndJava15() {
System.out.println("Shouldn't be run on Java 14 and 15.");
LOGGER.debug("Shouldn't be run on Java 14 and 15.");
}
@Test
@DisabledOnJre(JRE.OTHER)
public void thisTestOnlyRunsWithUpToDateJREs() {
System.out.println("this test will only run on java8, 9, 10 and 11.");
LOGGER.debug("this test will only run on java8, 9, 10 and 11.");
}
@Test
@EnabledIfSystemProperty(named = "java.vm.vendor", matches = "Oracle.*")
public void onlyIfVendorNameStartsWithOracle() {
System.out.println("runs only if vendor name starts with Oracle");
LOGGER.debug("runs only if vendor name starts with Oracle");
}
@Test
@DisabledIfSystemProperty(named = "file.separator", matches = "[/]")
public void disabledIfFileSeperatorIsSlash() {
System.out.println("Will not run if file.sepeartor property is /");
LOGGER.debug("Will not run if file.sepeartor property is /");
}
@Test
@EnabledIfEnvironmentVariable(named = "GDMSESSION", matches = "ubuntu")
public void onlyRunOnUbuntuServer() {
System.out.println("only runs if GDMSESSION is ubuntu");
LOGGER.debug("only runs if GDMSESSION is ubuntu");
}
@Test
@DisabledIfEnvironmentVariable(named = "LC_TIME", matches = ".*UTF-8.")
public void shouldNotRunWhenTimeIsNotUTF8() {
System.out.println("will not run if environment variable LC_TIME is UTF-8");
LOGGER.debug("will not run if environment variable LC_TIME is UTF-8");
}
// Commented codes are going to work prior JUnit 5.5
@ -76,13 +91,13 @@ public class ConditionalAnnotationsUnitTest {
@Test
// @EnabledIf("'FR' == systemProperty.get('user.country')")
public void onlyFrenchPeopleWillRunThisMethod() {
System.out.println("will run only if user.country is FR");
LOGGER.debug("will run only if user.country is FR");
}
@Test
// @DisabledIf("java.lang.System.getProperty('os.name').toLowerCase().contains('mac')")
public void shouldNotRunOnMacOS() {
System.out.println("will not run if our os.name is mac");
LOGGER.debug("will not run if our os.name is mac");
}
@Test
@ -97,14 +112,14 @@ public class ConditionalAnnotationsUnitTest {
engine = "nashorn",
reason = "Self-fulfilling: {result}")*/
public void onlyRunsInFebruary() {
System.out.println("this test only runs in February");
LOGGER.debug("this test only runs in February");
}
@Test
/*@DisabledIf("systemEnvironment.get('XPC_SERVICE_NAME') != null " +
"&& systemEnvironment.get('XPC_SERVICE_NAME').contains('intellij')")*/
public void notValidForIntelliJ() {
System.out.println("this test will run if our ide is INTELLIJ");
LOGGER.debug("this test will run if our ide is INTELLIJ");
}
@Target(ElementType.METHOD)
@ -117,7 +132,7 @@ public class ConditionalAnnotationsUnitTest {
@ThisTestWillOnlyRunAtLinuxAndMacWithJava9Or10Or11
public void someSuperTestMethodHere() {
System.out.println("this method will run with java9, 10, 11 and Linux or macOS.");
LOGGER.debug("this method will run with java9, 10, 11 and Linux or macOS.");
}
@Target(ElementType.METHOD)
@ -129,6 +144,6 @@ public class ConditionalAnnotationsUnitTest {
@RepeatedTest(2)
@CoinToss
public void gamble() {
System.out.println("This tests run status is a gamble with %50 rate");
LOGGER.debug("This tests run status is a gamble with %50 rate");
}
}

View File

@ -3,11 +3,16 @@ package com.baeldung.junit5.templates;
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
import org.junit.jupiter.api.extension.ExecutionCondition;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Properties;
public class DisabledOnQAEnvironmentExtension implements ExecutionCondition {
private static final Logger LOGGER = LoggerFactory.getLogger(DisabledOnQAEnvironmentExtension.class);
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
Properties properties = new Properties();
@ -16,7 +21,7 @@ public class DisabledOnQAEnvironmentExtension implements ExecutionCondition {
.getResourceAsStream("application.properties"));
if ("qa".equalsIgnoreCase(properties.getProperty("env"))) {
String reason = String.format("The test '%s' is disabled on QA environment", context.getDisplayName());
System.out.println(reason);
LOGGER.debug(reason);
return ConditionEvaluationResult.disabled(reason);
}
} catch (IOException e) {

View File

@ -1,6 +1,15 @@
package com.baeldung.junit5.templates;
import org.junit.jupiter.api.extension.*;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.BeforeTestExecutionCallback;
import org.junit.jupiter.api.extension.Extension;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContext;
import org.junit.jupiter.api.extension.TestTemplateInvocationContextProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.stream.Stream;
@ -9,6 +18,8 @@ import static java.util.Arrays.asList;
public class UserIdGeneratorTestInvocationContextProvider implements TestTemplateInvocationContextProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(UserIdGeneratorTestInvocationContextProvider.class);
@Override
public boolean supportsTestTemplate(ExtensionContext extensionContext) {
return true;
@ -44,13 +55,13 @@ public class UserIdGeneratorTestInvocationContextProvider implements TestTemplat
new BeforeTestExecutionCallback() {
@Override
public void beforeTestExecution(ExtensionContext extensionContext) {
System.out.println("BeforeTestExecutionCallback:Disabled context");
LOGGER.debug("BeforeTestExecutionCallback:Disabled context");
}
},
new AfterTestExecutionCallback() {
@Override
public void afterTestExecution(ExtensionContext extensionContext) {
System.out.println("AfterTestExecutionCallback:Disabled context");
LOGGER.debug("AfterTestExecutionCallback:Disabled context");
}
});
}
@ -72,13 +83,13 @@ public class UserIdGeneratorTestInvocationContextProvider implements TestTemplat
new BeforeEachCallback() {
@Override
public void beforeEach(ExtensionContext extensionContext) {
System.out.println("BeforeEachCallback:Enabled context");
LOGGER.debug("BeforeEachCallback:Enabled context");
}
},
new AfterEachCallback() {
@Override
public void afterEach(ExtensionContext extensionContext) {
System.out.println("AfterEachCallback:Enabled context");
LOGGER.debug("AfterEachCallback:Enabled context");
}
});
}

View File

@ -4,7 +4,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BusinessWorker {
private static Logger LOGGER = LoggerFactory.getLogger(BusinessWorker.class);
private static final Logger LOGGER = LoggerFactory.getLogger(BusinessWorker.class);
public void generateLogs(String msg) {
LOGGER.trace(msg);