Spring bean from test profile in JUnit 5 test class is not injected

1668 views java
-5

I would like to use in my jUnit 5 test class

@SpringBootTest
@RunWith(JUnitPlatform.class)
@ActiveProfiles("localtest")
class WorkreportDbRepositoryTest {

  @Autowired
  private SystemPriceSettingService systemPriceSettingService;

// the rest omitted .... 

}

a bean created in configuration for testing environment:

@Profile("localtest")
@Configuration
public class TestConfig {

  @Bean
  public SystemPriceSettingService systemPriceSettingService(){
    return new MemoryPriceSettingService();
  }

}

But the SystemPriceSettingService bean is not injected. What's wrong with my setup?

answered question

You forgot to annotate it with @ExtendWith(SpringExtension.class)

1 Answer

13

You don't use a JUnit Runner that is Spring aware. So no Spring context is created.
You should replace it the annotations on the test class such as :

import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@SpringBootTest
@ExtendWith(SpringExtension.class)
@ActiveProfiles("localtest")
class WorkreportDbRepositoryTest { ...}

And add this dependency to be able to use SpringExtension :

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-junit-jupiter</artifactId>
    <version>2.18.0</version> <!-- your mockito version-->
    <scope>test</scope>
</dependency>

posted this

Have an answer?

JD

Please login first before posting an answer.