Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 533
abin peter Avatar asked Jun 27 '19 10:06

abin peter


People also ask

What is @ContextConfiguration in Spring boot?

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.


1 Answers

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;
like image 106
Suraj Muraleedharan Avatar answered Oct 05 '22 06:10

Suraj Muraleedharan