Search code examples
springspring-bootmockitolog4jjunit5

When Junit Test with Spring throws Caused by: org.apache.logging.log4j.LoggingException: log4j-slf4j-impl cannot be present with log4j-to-slf4j


My service is running fine, but when I write a test it gives the error I specified. I tried several methods but couldn't find the problem.

dependency

<spring-boot.version>2.7.4</spring-boot.version>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

My Bussiness class

public class UserBusinessService {

    static Logger logger = LogFactory.getLogger(UserBusinessService.class);

    private final UserRepository userRepository;

    public UserBusinessService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void deleteUser(Long id) {
        userRepository.deleteUserByUserId(id);
        logger.info("deleted");
    }
}

MY Test Class

@ExtendWith(MockitoExtension.class)
class UserBusinessServiceTest {
    @Mock
    UserRepository userRepository;

    @InjectMocks
    UserBusinessService userBusinessService;


    @Test
    void deleteUser_itShouldReturnStatusNotFound_whenUserNotExist() throws Exception {

        // given
        when(userRepository.deleteUserByUserId(anyLong()));

        // when
        Executable executable = () -> userBusinessService.deleteUser(1L);

        // then
        assertThrows(BusinessException.class, executable);
    }
}

how can i fix this problem?


Solution

  • This problem was fixed by exclusion like this.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.apache.logging.log4j</groupId>
                <artifactId>log4j-to-slf4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>