0

我在运行我的测试类时遇到问题。我运行它后它返回“ 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();
        }
    }
}

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

4

1 回答 1

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
    }

}
于 2021-05-31T11:41:19.993 回答