Integrating Logging Frameworks and Testing Support in Spring 5
Spring 5 includes built-in abstractions for loggging and allows integration with custom logging libraries. The framework has deprecated LOG4jConfigListener and recommends using Log4j 2 for logging.
Integrating Log4j 2
Include the necessayr dependencies:
<!-- Log4j 2 SLF4J binding (transitive dependency includes core Log4j 2) -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.14.0</version>
<scope>test</scope>
</dependency>
Place a log4j2.xml configuration file under src/main/resources:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Appenders>
<Console name="StdOutLogger" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="StdOutLogger" />
</Root>
</Loggers>
</Configuration>
Testing Support in Spring 5
Using JUnit 4
Add the required test dependencies:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.5</version>
<scope>test</scope>
</dependency>
Example test class:
package com.example.tests;
import com.example.config.AppCfg;
import com.example.service.FinanceService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:app-context.xml")
public class FinanceServiceJUnit4Test {
@Autowired
private FinanceService financeSvc;
@Test
public void performTransfer() {
int result = financeSvc.moveFunds(10, 20, 250);
System.out.println(result);
}
}
Using JUnit 5
Declare JUnit 5 dependencies:
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.7.0</version>
<scope>test</scope>
</dependency>
Example test class with JUnit 5:
package com.example.tests;
import com.example.service.FinanceService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig(locations = "classpath:app-context.xml")
public class FinanceServiceJUnit5Test {
@Autowired
private FinanceService financeSvc;
@Test
public void performTransfer() {
int result = financeSvc.moveFunds(10, 20, 250);
System.out.println(result);
}
}