dani
dani

Reputation: 25

ApplicationContext returns null in SpringBootTest run with SpringRunner.class

I have a problem of running my Test class. It 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" this exception after I run it.

Here's my test 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);
    }

}

And my other classes are like;

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

Why I get the error after running the test application?

Upvotes: 0

Views: 1499

Answers (1)

Artem Duk
Artem Duk

Reputation: 26

Try to remove @Component annotation from the SftsImpl bean. @Service is enough to register a bean.

Also if you just want to test your bean - getting it from ApplicationContext maybe is not the best option. Code example of a unit test without using ApplicationContext:

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

    @Autowired
    Sfts sfts;

    @Test
    public void testAsync() {
        sfts.process();
        // do assertions here
    }

}

Upvotes: 1

Related Questions