HKAK
HKAK

Reputation: 99

How to access application.property variable value into test class

I am using spring data jpa for creating microservices. I am trying to write test cases for controller. Now In controller url I am accessing InstituteIdentifier variable value from application.property file. In AccountController class I am getting InstituteIdentifier variable value in url

But I am not able to access that InstituteIdentifier variable value in test class url. I tried using $ InstituteIdentifier in test case url but value is not injecting and I am getting 404 test case failure error.

Instead of accessing variable in url if I am hard coding InstituteIdentifier value then test case running without any error. But I don't want to hard code.

application.property file I am having in src/main directory. Can any one tell me how to access that application.property file variable in test class? or I need to create separate property file for test also.

AccountController

@RestController
@CrossOrigin(origins = "${crossOrigin}")
@RequestMapping("/spacestudy/${InstituteIdentifier}/admin/account")
public class AccountController {

    @Autowired
    AccountService accService;


    @GetMapping("/loadAcctLocationList")
    public ResponseEntity<List<Account>> findLocation() throws Exception{

        return  ResponseEntity.ok(accService.findLocation());

    }

TestAccountController

@RunWith(SpringRunner.class)
@WebMvcTest(value=AccountController.class)
public class TestAccountController {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private AccountService accountService;

        @Test
        public void findLocationTest() throws Exception {

            Account account = new Account();
            account.setsLocation("Test1");

            List<Account> accountObj = new ArrayList<Account>();
            accountObj.add(account);    

            Mockito.when(accountService.findLocation()).thenReturn(accountObj);

            mockMvc.perform(get("/spacestudy/$ InstituteIdentifier/admin/account/loadAcctLocationList"))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$[0].sLocation", is("Test1")))
                    .andExpect(jsonPath("$.*",Matchers.hasSize(1)));    

            for(Account result: accountObj) {

                assertEquals("Test1", result.sLocation);

            }

            }

Upvotes: 1

Views: 1938

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36143

You have to inject the property using the Value annotation and then use it to build the URL.

@Value("${InstituteIdentifier}")
private String instituteIdentifier;

Upvotes: 2

Related Questions