首页 > 解决方案 > 为什么@MockBean ConversionService 会导致错误

问题描述

给定:使用 Intellij IDEA Ultimate 创建的 JUnit 5 和空 SpringBoot 项目。对于带有包含@Autowired ConversionService 的控制器的项目,我得到了相同的结果。

我需要在测试中使用 ConversionService 的模拟版本。

这是我的方法:

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() {}
}

上面的代码导致错误:

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")}

此错误的原因是什么,解决方案是什么?

标签: spring-bootjunitmocking

解决方案


解决方案是用@SpyBean 替换@MockBean。


推荐阅读