Spring Boot 测试运行时在控制台上显示日志

问题描述 投票:0回答:1

当我通过

./gradlew test
在 Spring Boot v3.3.4 应用程序中运行测试时,控制台仅显示每个测试的名称和结果,例如

com.myapp.util.StringUtilsTests

大写NullAndEmptyStrings(字符串)

Test [1] input=null PASSED
Test [2] input= PASSED

将单词大写(字符串,字符串)

Test [1] input=FOO, expectedOutput=Foo PASSED
Test [2] input=foo, expectedOutput=Foo PASSED
Test [3] input=f, expectedOutput=F PASSED

不会显示应用程序或测试生成的任何日志记录。

运行测试后我唯一能找到日志消息的地方是

build/test-results/test
中的 XML 文件。为每个测试类创建一个 XML 文件,例如
TEST-com.myapp.util.StringUtilsTests.xml
用于上述测试。

我想在控制台上看到日志记录,就像应用程序运行时一样。我的应用程序的日志记录配置如下所示

logging:
  level:
    root: INFO
    com.myapp: DEBUG
    org.hibernate.envers: WARN 
    org.zalando.logbook: TRACE
java spring-boot gradle logging
1个回答
0
投票

解决方案之一可能是, 在你的java类中实现日志记录

UserService.java 

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    Logger logger = LoggerFactory.getLogger(UserService.class);

    public User createUser(User user) {
        logger.info("Creating a new user with email: {}", user.getEmail());
        try {
            User createdUser = userRepository.save(user);
            logger.info("Successfully created user with ID: {}", createdUser.getId());
            return createdUser;
        } catch (Exception e) {
            logger.error("Error while creating user with email: {}", user.getEmail(), e);
            throw e;
        }
    }

    public Optional<User> getUserByEmail(String email) {
        logger.info("Fetching user by email: {}", email);
        try {
            Optional<User> user = userRepository.findByEmail(email);
            if (user.isPresent()) {
                logger.info("User found with email: {}", email);
            } else {
                logger.warn("No user found with email: {}", email);
            }
            return user;
        } catch (Exception e) {
            logger.error("Error while fetching user by email: {}", email, e);
            throw e;
        }
    }

    public List<User> getAllUsers() {
        logger.info("Fetching all users from the database");
        try {
            List<User> users = userRepository.findAll();
            logger.info("Successfully fetched {} users", users.size());
            return users;
        } catch (Exception e) {
            logger.error("Error while fetching all users", e);
            throw e;
        }
    }
}

以及上述类的测试实现

UserServiceTest.java

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

class UserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserServiceTest.class);

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
    }

    @Test
    void testCreateUser() {
    
        User user = new User(1L, "John Doe", "[email protected]", "password123", "user");
        Mockito.when(userRepository.save(any(User.class))).thenReturn(user);
        
        User createdUser = userService.createUser(user);
        
        assertThat(createdUser).isNotNull();
        assertThat(createdUser.getId()).isEqualTo(1L);
        assertThat(createdUser.getName()).isEqualTo("John Doe");
        Mockito.verify(userRepository, Mockito.times(1)).save(user);
    }

    @Test
    void testGetUserByEmail_UserFound() {
        
        User user = new User(1L, "Jane Doe", "[email protected]", "password123", "admin");
        Mockito.when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.of(user));
        
        Optional<User> result = userService.getUserByEmail("[email protected]");
        
        assertThat(result).isPresent();
        assertThat(result.get().getEmail()).isEqualTo("[email protected]");
        Mockito.verify(userRepository, Mockito.times(1)).findByEmail("[email protected]");
    }

    @Test
    void testGetUserByEmail_UserNotFound() {
        Mockito.when(userRepository.findByEmail("[email protected]")).thenReturn(Optional.empty());
        
        Optional<User> result = userService.getUserByEmail("[email protected]");
        
        assertThat(result).isNotPresent();
        Mockito.verify(userRepository, Mockito.times(1)).findByEmail("[email protected]");
    }

    @Test
    void testGetAllUsers() {
        User user1 = new User(1L, "Alice", "[email protected]", "password123", "user");
        User user2 = new User(2L, "Bob", "[email protected]", "password123", "admin");
        List<User> users = Arrays.asList(user1, user2);
        when(userRepository.findAll()).thenReturn(users);
        
        List<User> result = userService.getAllUsers();
        
        assertThat(result).hasSize(2);
        assertThat(result.get(0).getName()).isEqualTo("Alice");
        assertThat(result.get(1).getName()).isEqualTo("Bob");
        verify(userRepository, times(1)).findAll();
    }
}

现在,当我运行 ./gradlew test 时,它将在控制台中给出测试用例的日志..

[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 12.503 s - in com.fl.featureflags.FeatureFlagsApplicationTests
[INFO] Running com.fl.featureflags.UserManagement.service.UserServiceTest
2024-10-18T18:52:09.427+05:30  INFO 30808 --- [           main] c.f.f.U.service.UserService              : Fetching all users from the database
2024-10-18T18:52:09.427+05:30  INFO 30808 --- [           main] c.f.f.U.service.UserService              : Successfully fetched 2 users
2024-10-18T18:52:09.777+05:30  INFO 30808 --- [           main] c.f.f.U.service.UserService              : Fetching user by email: [email protected]
2024-10-18T18:52:09.791+05:30  INFO 30808 --- [           main] c.f.f.U.service.UserService              : User found with email: [email protected]
2024-10-18T18:52:09.823+05:30  INFO 30808 --- [           main] c.f.f.U.service.UserService              : Creating a new user with email: [email protected]
2024-10-18T18:52:09.823+05:30  INFO 30808 --- [           main] c.f.f.U.service.UserService              : Successfully created user with ID: 1
2024-10-18T18:52:09.854+05:30  INFO 30808 --- [           main] c.f.f.U.service.UserService              : Fetching user by email: [email protected]
2024-10-18T18:52:09.854+05:30  WARN 30808 --- [           main] c.f.f.U.service.UserService              : No user found with email: [email protected]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.129 s - in com.fl.featureflags.UserManagement.service.UserServiceTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  30.147 s
[INFO] Finished at: 2024-10-18T18:52:10+05:30
[INFO] ------------------------------------------------------------------------

image of logs in console

希望这可以解决您的问题..

© www.soinside.com 2019 - 2024. All rights reserved.