Home > Enterprise >  @Value coming as null in junit 5
@Value coming as null in junit 5

Time:10-30

I am testing my application but while running the test cases I am getting NUllPointer Exception as it's not able to map the value from YML file.

Can you please let me know how to achieve this ?

ControllerClass

class ControllerClass {

@Value("${app.items}")
String[] items; -- coming as null while running test cases

// remaing code 

}

application-test.yml

app:
 items: a, b, c, d

Test class

@SpringJUnitConfig
@SpringBootTest
@ActiveProfiles("test)
class TestControllerClass {

@InjectMock
ControllerClass controller;

@Mock
ServiceClass service;

@Test
//test case

}

CodePudding user response:

Mockito doesn't know what to do - you can do it manually though:

 @Before
    public void setUp() {
        String[] items = new String[2];
        items[0] = "a";
        items[1] = "b";
        ReflectionTestUtils.setField(controller, "items", 
               items);
    }

CodePudding user response:

Naturally, we'll need a properties file to define the values we want to inject with the @Value annotation. And so, we'll first need to define a @PropertySource in our configuration class — with the properties file name.

@PropertySource("classpath:values.properties")
class ControllerClass {

@Value("${app.items}")
String[] items; -- coming as null while running test cases

// remaing code 

}

if it is not working use . properties file like mentioned here.

  • Related