简体   繁体   中英

Beans not injected into jUnit test

I have a problem with proper Spring Beans configuration. My whole app works properly with Spring and I wanted to add jUnit tests. Unfortunately, beans are not injected properly. I have two directories inside same module. My whole app is inside:

/src/main/java/main/

which works correctly and I added RestTest.java and BeanTestConfiguration.java inside:

/src/test/java/main/

@SpringBootTest
@RunWith(Spring.Runner.class)
@ContextConfiguration(classes=BeanTestConfiguration.class)
class RestTest {

    @Autowired
    public String testString;


    @Test
    public void send() {
        System.out.println(testString);
        Assert.assertNotNull(testString);
    }
}

And config BeanTestConfiguration

@Configuration
public class BeanTestConfiguration {
    @Bean
    public String testString() { return new String("Hello"); }
}

Unfortunately, when I run test on send method System out prints null, and Assert throws fail. I added Spring Application Context to Project Structure inside IntelliJ

As your test class and method is package private I assume you are using jUnit 5. In jUnit 5 instead of @RunWith you should use the @ExtendWith annotation. In particular the SpringExtension

By annotating test classes with @ExtendWith(SpringExtension.class), developers can implement standard JUnit Jupiter based unit and integration tests and simultaneously reap the benefits of the TestContext framework such as support for loading application contexts, dependency injection of test instances, transactional test method execution, and so on.

https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-junit-jupiter-extension

Eg

@SpringBootTest
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes=BeanTestConfiguration.class)
class RestTest {

    @Autowired
    public String testString;


    @Test
    void send() {
        System.out.println(testString);
        Assert.assertNotNull(testString);
    }
}

Thank You all for help. I found out I had problem with the imports. My @Test annotation was from jUnit 5, whereas I had SpringRunner inside annotation which was from jUnit 4, as a result Spring wasn't working correctly and beans weren't injected.

One more time I want to thank You all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM