如何在测试用例HTTP方法URL中访问变量值

时间:2018-07-13 10:57:32

标签: junit spring-data-jpa application.properties

我正在尝试在spring boot jpa应用程序中为控制器类编写Junit测试用例。在控制器班 我正在InstituteIdentifier文件中像这样的${InstituteIdentifier}访问url中的application.property变量。在这里,我在url

中获得了该值

在测试案例中,我也使用InstituteIdentifier注释从application.property访问@value变量。我可以在控制台中打印该值。但是,当我在测试用例GET方法URL中访问该变量时,出现此错误java.lang.IllegalArgumentException: Not enough variable values available to expand 'InstituteIdentifier

搜索此错误时,我发现这里${InstituteIdentifier}不需要给出{}。当我删除{}变量值时,网址中未出现变量值。

有人可以告诉我该怎么做吗?

application.property

InstituteIdentifier=vcufy2010

DepartmenController

@RestController
@CrossOrigin(origins ="${crossOrigin}")
@RequestMapping("/spacestudy/${InstituteIdentifier}/control/searchfilter")
public class DepartmentController {

    @Autowired
    DepartmentService depService;

    @GetMapping("/loadDepartments")
    public ResponseEntity<Set<Department>> findDepName() {

        Set<Department> depname = depService.findDepName();

        return ResponseEntity.ok(depname);
    }   
}

TestDepartmentController

@RunWith(SpringRunner.class)
@WebMvcTest(value=DepartmentController.class)
public class TestDepartmentController {

    @Autowired
    private MockMvc  mockMvc;

    @MockBean
    DepartmentService departmentService;

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

    @Test
    public void testfindDepName() throws Exception {

        System.out.println(InstituteIdentifier);//vcufy2010

        Department department = new Department();       
        department.setsDeptName("ABC");


        Set<Department> departmentObj = new HashSet<Department>();
        departmentObj.add(department);

        Mockito.when(departmentService.findDepName()).thenReturn(departmentObj);

        mockMvc.perform(get("/spacestudy/${InstituteIdentifier}/control/searchfilter/loadDepartments")
                            .accept(MediaType.APPLICATION_JSON))

1 个答案:

答案 0 :(得分:0)

  

搜索此错误时,我发现这里是$ {InstituteIdentifier}   我们不需要给{}。当我删除{}变量值不是   欺骗网址。

要使用String变量的值,则不需要{}$
实际上,您不需要进行任何评估。多亏了Spring的@Value才做到了。

所以在您的测试中,这是正确的:

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

,因为您需要从已加载的属性中检索值。

然后,您只需通过串联instituteIdentifier来在提交的URL中传递String变量的值:

mockMvc.perform(get("/spacestudy/" + instituteIdentifier +  "/control/searchfilter/loadDepartments")
                            .accept(MediaType.APPLICATION_JSON))