Reputation: 280
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
Upvotes: 1
Views: 7840
Reputation: 280
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.
Upvotes: 2
Reputation: 6771
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.
E.g.
@SpringBootTest
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes=BeanTestConfiguration.class)
class RestTest {
@Autowired
public String testString;
@Test
void send() {
System.out.println(testString);
Assert.assertNotNull(testString);
}
}
Upvotes: 0