Unable to create beans for testing using @ContextConfiguration in junit 5

abin peter :

I am trying to write junit test cases for my application.After using Junit 5, I am unable to create the necessary beans by using @ContextConfiguration.

It didn't throw any error. But while Autowiring the beans in the testing class I got null values

I have added the following dependencies

testImplementation "org.junit.jupiter:junit-jupiter-api:5.3.0"
testCompile('org.junit.jupiter:junit-jupiter-params:5.3.0')
testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.3.0"

and my code

@ContextConfiguration(classes = ServiceTestContextConfiguration.class)
public class ApplicationConfigTest {

@Autowired
private ApplicationServiceConfiguration 

applicationServiceConfiguration;

@ContextConfiguration
public class ServiceTestContextConfiguration {
@Bean
public ApplicationServiceConfiguration applicationServiceConfiguration() {
    return new ApplicationServiceConfiguration();
}

i am using spring-boot 2.

Suraj Muraleedharan :

May be we mixed the imports of junit4 with junit5. Let's annotate the configuration class with @Configuration (org.springframework.context.annotation.Configuration;).

In the main unit test, let's use the following,

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = ServiceTestContextConfiguration.class)

Instead of @Before, use @BeforeEach and make sure all imports are from junit5 (including assertions)

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130882&siteId=1