【问题标题】:ApplicationContext returns null in SpringBootTest run with SpringRunner.classApplicationContext 在使用 SpringRunner.class 运行的 SpringBootTest 中返回 null
【发布时间】:2021-08-18 17:07:02
【问题描述】:

我在运行我的测试类时遇到问题。我运行它后它返回“org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 't.c.i.s.se.Sfts' available: expected single matching bean but found 2: sftsImpl,sfts”这个异常。

这是我的测试课;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Sfta.class)
public class SftaTests {

    @Autowired
    ApplicationContext ac;

    @Test
    public void contextLoads() {
        Sfts sfts= ac.getBean(Sfts.class);
        assertTrue(Sfts instanceof SftsImpl);
    }

}

而我的其他课程是这样的;

public interface Sfts {

    public void process();
}

@Service
@Component
public class SftsImpl implements Sfts {

    @Autowired
    private GlobalConfig globalConfig;

    @Autowired
    private Ftr ftr;

    private Fc fc;

    @Async
    @Scheduled(initialDelayString = "${s.f.t.m}", fixedRateString = "${s.f.t.m}")
    public void process() {
        int hod = DateTime.now().getHourOfDay();
        if (hod != 6){
            fc = new Fc(globalConfig, ftr);
            fc.control();
        }
    }
}

为什么我在运行测试应用程序后会收到错误消息?

【问题讨论】:

    标签: java junit spring-test spring-boot-test springrunner


    【解决方案1】:

    尝试从 SftsImpl bean 中删除 @Component 注释。 @Service 足以注册一个 bean。

    此外,如果您只是想测试您的 bean - 从 ApplicationContext 获取它可能不是最佳选择。 不使用 ApplicationContext 的单元测试代码示例:

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = Sfta.class)
    public class SftaTests {
    
        @Autowired
        Sfts sfts;
    
        @Test
        public void testAsync() {
            sfts.process();
            // do assertions here
        }
    
    }
    

    【讨论】:

    • 现在我的getBean 返回对象的Proxy 实例而不是SftsImpl 的实例。为什么会返回Proxy?
    • 我认为这是由于@Async注解,Spring创建了一个代理以便在那里实现异步逻辑。
    • 是的,你是对的,但我如何测试 @Async 方法?我需要在我的代码中进行哪些更改?
    • 您可以将您的类自动装配到测试类中,然后调用您的方法。
    • 或者,如果你想使用应用程序上下文 - 你可以使用类转换。
    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2016-12-14
    • 2021-07-30
    • 2020-01-21
    • 2021-12-25
    相关资源
    最近更新 更多