1

When i run my junit for Rest Controller class, properties in Rest controller is throwing Nullpointer exception. Below is my sample code. when i run the testFileStatus() method of TestingControllerTest calass, i am getting Nullpointer exception. Kindly help to resolve the issue. Any suggestion why i can't able to access the property even though it is available in test application.properties.

enter image description here

@RestController
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class TestingController {
    @Value("${file.dir.status}")
    private String fileDirectoryStatus;

    @GetMapping(value="/filedetails")
    public String getFileDetails(.....){
        if(fileDirectoryStatus.equalsIgnoreCase("true")) {         //NullpointerException in Junit test
        //code to process file
        }
    }
}

src/main/resources/application.properties:

file.dir.status=false

src/test/resources/application.properties:

file.dir.status=false
@SpringBootTest
@TestPropertySource(
locations = "classpath:resources/application.properties")
public class TestingControllerTest{
    @InjectMocks
    private TestingController testingController; 

    @Test
    public void testFileStatus() {
    String status=testingController.getFileDetails(...);
    }
}
M. Deinum
  • 115,695
  • 22
  • 220
  • 224
  • Ofcourse it is `null`. you should `@Autowire` it nog `@InjectMocks` as that is for a plain Mockito test. – M. Deinum Jun 04 '21 at 07:30
  • No i want to use only mocking. is there any to make it work like get the properties value in test case which is used on controller. – user7241884 Jun 07 '21 at 09:35
  • If you only want mocking you cannot use spring features. You are trying to mix things in a wrong way. As stated use `@Autowired` instead of `@InjectMocks` (those are different annotations for different purposes), remove `SpringBootTest` and use `@WebMvcTest` (and readup on what those annotations actually do/meain instead of blindly following guides on the internet). – M. Deinum Jun 07 '21 at 11:42

0 Answers0