G
G
godmodeon082017-11-05 18:01:38
Java
godmodeon08, 2017-11-05 18:01:38

How to test spring @component?

Hey!
Relatively speaking, there is a class:

@Component
public class TelegramBot extends TelegramLongPollingBot implements InitializingBean {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(TelegramBot.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Autowired
    private TelegramDao telegramDao;

    @Value("${spring.botusername}")
    private String botUserName;

    @Value("${spring.bottoken}")
    private String botToken;
 


    public void sendMessage(Chat chat, String message) {
    
    }
 
}

I want to test calling the sendMessage method.
Wrote a test:
@RunWith(SpringJUnit4ClassRunner.class)

public class TelegramTest {

    @Autowired
    @Qualifier("bot")
    private TelegramBot telegramBot;




    @Test
    public void test1(){
         telegramBot.sendMessage(null,null);
    }


}

I am getting an error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'telegram.TelegramTest': Unsatisfied dependency expressed through field 'telegramBot'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'TelegramBot' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=bot)}

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
godmodeon08, 2017-11-06
@godmodeon08

No, you should have done the test like this:

@RunWith(SpringRunner.class)
@SpringBootTest(classes={SpringBootApp.class})
public class TelegramTest {

    @Autowired
    private TelegramBot telegramBot;




    @Test
    public void test1(){
         telegramBot.sendMessage(null,null);
    }


}

Those in the class header updated the annotations to:
@RunWith(SpringRunner.class)
@SpringBootTest(classes={SpringBootApp.class})

And everything worked :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question