Why @MockBean ConversionService causes an error

Viewed 220

Given: JUnit 5 and empty SpringBoot project created with Intellij IDEA Ultimate. I get the same results for projects with a controller that contains @Autowired ConversionService.

I need to use in a test the mocked version of ConversionService.

This is my approach:

import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.convert.ConversionService;

@SpringBootTest
public class ConversionServiceTest {

    @MockBean
    ConversionService conversionService;

    @Test
    void test() {}
}

The above code causes the error:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.format.support.FormattingConversionService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Qualifier(value="mvcConversionService")}

What is the reason for this error and what is the solution?

1 Answers

The solution is to replace @MockBean by @SpyBean.

Related