SpringBootTest 运行 和 SpringRunner.class 中的 ApplicationContext returns 为空

ApplicationContext returns null in SpringBootTest run with SpringRunner.class

我在 运行 测试 class 时遇到问题。它returns“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”这个异常在我运行它之后。

这是我的测试 class;

@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);
    }

}

我的其他 class 就像;

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

为什么我在 运行 测试应用程序后出现错误?

尝试从 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
    }

}