BAEL-20888 Move Spring Boot Testing to Spring Boot Modules

This commit is contained in:
mikr
2020-01-26 23:09:20 +01:00
parent 9fd36e6fe8
commit 356f551acf
43 changed files with 2 additions and 3 deletions

View File

@@ -0,0 +1,14 @@
package com.baeldung.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
private static ApplicationContext applicationContext;
public static void main(String[] args) {
applicationContext = SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,14 @@
package com.baeldung.boot.controller.rest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@GetMapping("/")
public String salutation() {
return "Welcome !";
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.boot.controller.rest;
import java.util.Optional;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class WebController {
private String name;
@GetMapping
public String salutation() {
return "Hello " + Optional.ofNullable(name).orElse("world") + '!';
}
@PutMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
public void setName(@RequestBody final String name) {
this.name = name;
}
@DeleteMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
public void resetToDefault() {
this.name = null;
}
}

View File

@@ -0,0 +1,24 @@
package com.baeldung.boot.embeddedRedis.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
@Configuration
@EnableRedisRepositories
public class RedisConfiguration {
@Bean
public LettuceConnectionFactory redisConnectionFactory(final RedisProperties redisProperties) {
return new LettuceConnectionFactory(redisProperties.getRedisHost(), redisProperties.getRedisPort());
}
@Bean
public RedisTemplate<?, ?> redisTemplate(final LettuceConnectionFactory connectionFactory) {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
return template;
}
}

View File

@@ -0,0 +1,23 @@
package com.baeldung.boot.embeddedRedis.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedisProperties {
private final int redisPort;
private final String redisHost;
public RedisProperties(@Value("${spring.redis.port}") final int redisPort, @Value("${spring.redis.host}") final String redisHost) {
this.redisPort = redisPort;
this.redisHost = redisHost;
}
public int getRedisPort() {
return redisPort;
}
public String getRedisHost() {
return redisHost;
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.boot.embeddedRedis.domain;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import java.util.UUID;
@RedisHash("user")
public class User {
@Id private UUID id;
private String name;
public User(UUID id, String name) {
this.id = id;
this.name = name;
}
public UUID getId() {
return id;
}
public String getName() {
return name;
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.boot.embeddedRedis.domain.repository;
import com.baeldung.boot.embeddedRedis.domain.User;
import org.springframework.data.repository.CrudRepository;
import java.util.UUID;
public interface UserRepository extends CrudRepository<User, UUID> {
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class OtherComponent {
private static final Logger LOG = LoggerFactory.getLogger(OtherComponent.class);
public void processData() {
LOG.trace("This is a TRACE log from another package");
LOG.debug("This is a DEBUG log from another package");
LOG.info("This is an INFO log from another package");
LOG.error("This is an ERROR log from another package");
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.testloglevel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.baeldung.boot.Application;
@SpringBootApplication(scanBasePackages = {"com.baeldung.testloglevel", "com.baeldung.component"})
public class TestLogLevelApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.testloglevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.component.OtherComponent;
@RestController
public class TestLogLevelController {
private static final Logger LOG = LoggerFactory.getLogger(TestLogLevelController.class);
@Autowired
private OtherComponent otherComponent;
@GetMapping("/testLogLevel")
public String testLogLevel() {
LOG.trace("This is a TRACE log");
LOG.debug("This is a DEBUG log");
LOG.info("This is an INFO log");
LOG.error("This is an ERROR log");
otherComponent.processData();
return "Added some log output to console...";
}
}

View File

@@ -0,0 +1,3 @@
# test properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

View File

@@ -0,0 +1,7 @@
# embedded redis
spring.redis.host= localhost
spring.redis.port= 6379
# security
spring.security.user.name=john
spring.security.user.password=123

View File

@@ -0,0 +1,23 @@
package com.baeldung.boot
import com.baeldung.boot.controller.rest.WebController
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import spock.lang.Narrative
import spock.lang.Specification
import spock.lang.Title
@Title("Application Specification")
@Narrative("Specification which beans are expected")
@SpringBootTest
class LoadContextTest extends Specification {
@Autowired(required = false)
private WebController webController
def "when context is loaded then all expected beans are created"() {
expect: "the WebController is created"
webController
}
}

View File

@@ -0,0 +1,43 @@
package com.baeldung.boot
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import spock.lang.Narrative
import spock.lang.Specification
import spock.lang.Title
@Title("WebController Specification")
@Narrative("The Specification of the behaviour of the WebController. It can greet a person, change the name and reset it to 'world'")
@AutoConfigureMockMvc(secure=false)
@WebMvcTest()
class WebControllerTest extends Specification {
@Autowired
private MockMvc mvc
def "when get is performed then the response has status 200 and content is 'Hello world!'"() {
expect: "Status is 200 and the response is 'Hello world!'"
mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!"
}
def "when set and delete are performed then the response has status 204 and content changes as expected"() {
given: "a new name"
def NAME = "Emmy"
when: "the name is set"
mvc.perform(MockMvcRequestBuilders.put("/hello").content(NAME)).andExpect(MockMvcResultMatchers.status().isNoContent())
then: "the salutation uses the new name"
mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello $NAME!"
when: "the name is deleted"
mvc.perform(MockMvcRequestBuilders.delete("/hello")).andExpect(MockMvcResultMatchers.status().isNoContent())
then: "the salutation uses the default name"
mvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().response.contentAsString == "Hello world!"
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.autoconfig.exclude;
import com.baeldung.boot.Application;
import io.restassured.RestAssured;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration")
public class ExcludeAutoConfig1IntegrationTest {
/**
* Encapsulates the random port the test server is listening on.
*/
@LocalServerPort
private int port;
@Test
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
assertEquals(HttpStatus.OK.value(), statusCode);
}
}

View File

@@ -0,0 +1,32 @@
package com.baeldung.autoconfig.exclude;
import com.baeldung.boot.Application;
import io.restassured.RestAssured;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class ExcludeAutoConfig2IntegrationTest {
/**
* Encapsulates the random port the test server is listening on.
*/
@LocalServerPort
private int port;
@Test
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
assertEquals(HttpStatus.OK.value(), statusCode);
}
}

View File

@@ -0,0 +1,33 @@
package com.baeldung.autoconfig.exclude;
import com.baeldung.boot.Application;
import io.restassured.RestAssured;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@EnableAutoConfiguration(exclude=SecurityAutoConfiguration.class)
public class ExcludeAutoConfig3IntegrationTest {
/**
* Encapsulates the random port the test server is listening on.
*/
@LocalServerPort
private int port;
@Test
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
assertEquals(HttpStatus.OK.value(), statusCode);
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.autoconfig.exclude;
import io.restassured.RestAssured;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class ExcludeAutoConfig4IntegrationTest {
/**
* Encapsulates the random port the test server is listening on.
*/
@LocalServerPort
private int port;
@Test
public void givenSecurityConfigExcluded_whenAccessHome_thenNoAuthenticationRequired() {
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
assertEquals(HttpStatus.OK.value(), statusCode);
}
}

View File

@@ -0,0 +1,13 @@
package com.baeldung.autoconfig.exclude;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
@SpringBootApplication(scanBasePackages="com.baeldung.boot", exclude=SecurityAutoConfiguration.class)
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}

View File

@@ -0,0 +1,15 @@
package com.baeldung.boot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class SpringContextTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@@ -0,0 +1,36 @@
package com.baeldung.boot.autoconfig;
import com.baeldung.boot.Application;
import io.restassured.RestAssured;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertEquals;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class AutoConfigIntegrationTest {
/**
* Encapsulates the random port the test server is listening on.
*/
@LocalServerPort
private int port;
@Test
public void givenNoAuthentication_whenAccessHome_thenUnauthorized() {
int statusCode = RestAssured.get("http://localhost:" + port).statusCode();
assertEquals(HttpStatus.UNAUTHORIZED.value(), statusCode);
}
@Test
public void givenAuthentication_whenAccessHome_thenOK() {
int statusCode = RestAssured.given().auth().basic("john", "123").get("http://localhost:" + port).statusCode();
assertEquals(HttpStatus.OK.value(), statusCode);
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.boot.embeddedRedis;
import com.baeldung.boot.embeddedRedis.configuration.RedisProperties;
import org.springframework.boot.test.context.TestConfiguration;
import redis.embedded.RedisServer;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
@TestConfiguration
public class TestRedisConfiguration {
private final RedisServer redisServer;
public TestRedisConfiguration(final RedisProperties redisProperties) {
this.redisServer = new RedisServer(redisProperties.getRedisPort());
}
@PostConstruct
public void postConstruct() {
redisServer.start();
}
@PreDestroy
public void preDestroy() {
redisServer.stop();
}
}

View File

@@ -0,0 +1,31 @@
package com.baeldung.boot.embeddedRedis.domain.repository;
import com.baeldung.boot.embeddedRedis.TestRedisConfiguration;
import com.baeldung.boot.embeddedRedis.domain.User;
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.junit4.SpringRunner;
import java.util.UUID;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestRedisConfiguration.class)
public class UserRepositoryIntegrationTest {
@Autowired
private UserRepository userRepository;
@Test
public void shouldSaveUser_toRedis() {
final UUID id = UUID.randomUUID();
final User user = new User(id, "name");
final User saved = userRepository.save(user);
assertNotNull(saved);
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.testloglevel;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
@DirtiesContext(classMode = AFTER_CLASS)
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class)
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
@ActiveProfiles("logback-test2")
public class LogbackMultiProfileTestLogLevelIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Rule
public OutputCapture outputCapture = new OutputCapture();
private String baseUrl = "/testLogLevel";
@Test
public void givenErrorRootLevelAndTraceLevelForOurPackage_whenCall_thenPrintTraceLogsForOurPackage() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputContainsLogForOurPackage("TRACE");
}
@Test
public void givenErrorRootLevelAndTraceLevelForOurPackage_whenCall_thenNoTraceLogsForOtherPackages() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputDoesntContainLogForOtherPackages("TRACE");
}
@Test
public void givenErrorRootLevelAndTraceLevelForOurPackage_whenCall_thenPrintErrorLogs() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputContainsLogForOurPackage("ERROR");
assertThatOutputContainsLogForOtherPackages("ERROR");
}
private void assertThatOutputContainsLogForOurPackage(String level) {
assertThat(outputCapture.toString()).containsPattern("TestLogLevelController.*" + level + ".*");
}
private void assertThatOutputDoesntContainLogForOtherPackages(String level) {
assertThat(outputCapture.toString().replaceAll("(?m)^.*TestLogLevelController.*$", "")).doesNotContain(level);
}
private void assertThatOutputContainsLogForOtherPackages(String level) {
assertThat(outputCapture.toString().replaceAll("(?m)^.*TestLogLevelController.*$", "")).contains(level);
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.testloglevel;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
@DirtiesContext(classMode = AFTER_CLASS)
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class)
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
@ActiveProfiles("logback-test")
public class LogbackTestLogLevelIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Rule
public OutputCapture outputCapture = new OutputCapture();
private String baseUrl = "/testLogLevel";
@Test
public void givenErrorRootLevelAndDebugLevelForOurPackage_whenCall_thenPrintDebugLogsForOurPackage() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputContainsLogForOurPackage("DEBUG");
}
@Test
public void givenErrorRootLevelAndDebugLevelForOurPackage_whenCall_thenNoDebugLogsForOtherPackages() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputDoesntContainLogForOtherPackages("DEBUG");
}
@Test
public void givenErrorRootLevelAndDebugLevelForOurPackage_whenCall_thenPrintErrorLogs() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputContainsLogForOurPackage("ERROR");
assertThatOutputContainsLogForOtherPackages("ERROR");
}
private void assertThatOutputContainsLogForOurPackage(String level) {
assertThat(outputCapture.toString()).containsPattern("TestLogLevelController.*" + level + ".*");
}
private void assertThatOutputDoesntContainLogForOtherPackages(String level) {
assertThat(outputCapture.toString().replaceAll("(?m)^.*TestLogLevelController.*$", "")).doesNotContain(level);
}
private void assertThatOutputContainsLogForOtherPackages(String level) {
assertThat(outputCapture.toString().replaceAll("(?m)^.*TestLogLevelController.*$", "")).contains(level);
}
}

View File

@@ -0,0 +1,73 @@
package com.baeldung.testloglevel;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
@RunWith(SpringRunner.class)
@DirtiesContext(classMode = AFTER_CLASS)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class)
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
@ActiveProfiles("logging-test")
public class TestLogLevelWithProfileIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Rule
public OutputCapture outputCapture = new OutputCapture();
private String baseUrl = "/testLogLevel";
@Test
public void givenInfoRootLevelAndDebugLevelForOurPackage_whenCall_thenPrintDebugLogsForOurPackage() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputContainsLogForOurPackage("DEBUG");
}
@Test
public void givenInfoRootLevelAndDebugLevelForOurPackage_whenCall_thenNoDebugLogsForOtherPackages() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputDoesntContainLogForOtherPackages("DEBUG");
}
@Test
public void givenInfoRootLevelAndDebugLevelForOurPackage_whenCall_thenPrintInfoLogs() {
ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
assertThat(response.getStatusCode().value()).isEqualTo(200);
assertThatOutputContainsLogForOurPackage("INFO");
assertThatOutputContainsLogForOtherPackages("INFO");
}
private void assertThatOutputContainsLogForOurPackage(String level) {
assertThat(outputCapture.toString()).containsPattern("TestLogLevelController.*" + level + ".*");
}
private void assertThatOutputDoesntContainLogForOtherPackages(String level) {
assertThat(outputCapture.toString().replaceAll("(?m)^.*TestLogLevelController.*$", "")).doesNotContain(level);
}
private void assertThatOutputContainsLogForOtherPackages(String level) {
assertThat(outputCapture.toString().replaceAll("(?m)^.*TestLogLevelController.*$", "")).contains(level);
}
}

View File

@@ -0,0 +1 @@
logging.config=classpath:logback-test.xml

View File

@@ -0,0 +1 @@
logging.config=classpath:logback-multiprofile.xml

View File

@@ -0,0 +1,2 @@
logging.level.com.baeldung.testloglevel=DEBUG
logging.level.root=INFO

View File

@@ -0,0 +1,2 @@
# test properties
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

View File

@@ -0,0 +1,6 @@
#embedded redis
spring.redis.host= localhost
spring.redis.port= 6370
# security
spring.security.user.name=john
spring.security.user.password=123

View File

@@ -0,0 +1,18 @@
<configuration>
<include resource="/org/springframework/boot/logging/logback/base.xml"/>
<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="error">
<appender-ref ref="STDOUT"/>
</root>
<springProfile name="logback-test1">
<logger name="com.baeldung.testloglevel" level="info"/>
</springProfile>
<springProfile name="logback-test2">
<logger name="com.baeldung.testloglevel" level="trace"/>
</springProfile>
</configuration>

View File

@@ -0,0 +1,13 @@
<configuration>
<include resource="/org/springframework/boot/logging/logback/base.xml"/>
<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="error">
<appender-ref ref="STDOUT"/>
</root>
<logger name="com.baeldung.testloglevel" level="debug"/>
</configuration>