Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring测试-java.lang.IllegalArgumentException:没有足够的变量值可供扩展_Java_Spring_Junit_Spring Test - Fatal编程技术网

Spring测试-java.lang.IllegalArgumentException:没有足够的变量值可供扩展

Spring测试-java.lang.IllegalArgumentException:没有足够的变量值可供扩展,java,spring,junit,spring-test,Java,Spring,Junit,Spring Test,我正在为下面的REST控制器编写单元测试,它接受一个用户ID并向该用户授予一个权限列表 @RestController @RequestMapping("/user") @Api(value = "User", description = "User API") public class UserController{ // some code @RequestMapping(method = RequestMethod.POST, v

我正在为下面的REST控制器编写单元测试,它接受一个用户ID并向该用户授予一个权限列表

    @RestController
    @RequestMapping("/user")
    @Api(value = "User", description = "User API")
    public class UserController{

    // some code

        @RequestMapping(method = RequestMethod.POST, value = "/{userId}/grantAuthz")
        @ApiOperation(value = "GrantAuthz", notes = "Grant Authorization")
        public Collection<UserEntity.UserAuthz> grantAuthz(@PathVariable("userId") String userId,
                                                           @RequestBody ArrayList<String> authorities) {
            UserEntity userEntity = userRepository.findOne(userId);
            if(userEntity == null) {
                //TODO: throw and send resource not found
                return null;
            }
            log.debug("Authorities to be granted to user " + userId + " are : " + authorities);
            for(String authz : authorities) {
                log.debug("Adding Authorization " + authz);
                userEntity.addUserAuthz(authz);
            }
            userRepository.save(userEntity);
            return userEntity.getAuthorities();
        }
}
@RestController
@请求映射(“/user”)
@Api(value=“用户”,description=“用户Api”)
公共类用户控制器{
//一些代码
@RequestMapping(method=RequestMethod.POST,value=“/{userId}/grantAuthz”)
@ApiOperation(value=“GrantAuthz”,notes=“授权”)
公共集合grantAuthz(@PathVariable(“userId”)字符串userId,
@请求主体(ArrayList权限){
UserEntity UserEntity=userRepository.findOne(userId);
if(userEntity==null){
//TODO:未找到抛出和发送资源
返回null;
}
log.debug(“授予用户的权限”+userId+”为:“+Authorities”);
用于(字符串身份验证:权限){
log.debug(“添加授权”+authz);
userEntity.addUserAuthz(authz);
}
userRepository.save(userEntity);
返回userEntity.getAuthories();
}
}
我为UserController编写了下面的单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class UserControllerTest {
    private final Log log = LogFactory.getLog(getClass());
    private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
            MediaType.APPLICATION_JSON.getSubtype(),
            Charset.forName("utf8"));

    private MockMvc mockMvc;
    private HttpMessageConverter mappingJackson2HttpMessageConverter;
    private final String USER_URL = "/{userId}/grantAuthz";
    private final String USER_ID = "111";
    private final String USER_NAME = "MockUser";

    @Autowired
    private WebApplicationContext webApplicationContext;
    @Autowired
    private UserRepository userRepository;

    private String createdToken = null;

    @Autowired
    void setConverters(HttpMessageConverter<?>[] converters) {
        this.mappingJackson2HttpMessageConverter = Arrays.asList(converters).stream().filter(
                hmc -> hmc instanceof MappingJackson2HttpMessageConverter).findAny().get();

        Assert.assertNotNull("the JSON message converter must not be null",
                this.mappingJackson2HttpMessageConverter);
    }

    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testGrantAuthorizationForUser() throws Exception{
        Optional<UserEntity> userEntityAuthz = userRepository.findOneByUsername(USER_NAME);
        Set<String> expectedAuthzList = (LinkedHashSet)userEntityAuthz.get().getAuthorizations();

        List<String> grantList = new ArrayList<>();
        grantList.add("ABC");
        grantList.add("DEF");
        grantList.add("GHI");
        grantList.add("JKL");
        grantList.add("MNO");
        grantList.add("PQR");
        grantList.add("STU");
        grantList.add("VWX");
        grantList.add("YZA");

        JSONObject json = new JSONObject();
        json.put("grantList",grantList);

        MvcResult grantAuthzResult = mockMvc.perform(MockMvcRequestBuilders.post(USER_URL)
                .contentType(contentType)
                .param("userId",USER_ID)
                .param("authorities",json.toString()))
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(类=Application.class)
@WebAppConfiguration
公共类UserControllerTest{
私有最终日志Log=LogFactory.getLog(getClass());
私有MediaType contentType=新的MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
字符集forName(“utf8”);
私有MockMvc-MockMvc;
私有HttpMessageConverter映射Jackson2HttpMessageConverter;
私有最终字符串USER_URL=“/{userId}/grantAuthz”;
私有最终字符串用户\u ID=“111”;
私有最终字符串USER_NAME=“MockUser”;
@自动连线
私有WebApplicationContext WebApplicationContext;
@自动连线
私有用户存储库用户存储库;
私有字符串createdToken=null;
@自动连线
void setConverters(HttpMessageConverter[]转换器){
this.mappingJackson2HttpMessageConverter=Arrays.asList(converters).stream().filter(
hmc->hmc instanceof MappingJackson2HttpMessageConverter.findAny().get();
Assert.assertNotNull(“JSON消息转换器不能为null”,
此.mappingJackson2HttpMessageConverter);
}
@以前
public void setup()引发异常{
this.mockMvc=webAppContextSetup(webApplicationContext.build();
}
@试验
public void testGrantAuthorizationForUser()引发异常{
可选userEntityAuthz=userRepository.findOneByUsername(用户名);
Set expectedAuthzList=(LinkedHashSet)userEntityAuthz.get().getAuthorizations();
List grantList=new ArrayList();
授权列表。添加(“ABC”);
授权列表。添加(“DEF”);
赠款清单。添加(“GHI”);
授权列表。添加(“JKL”);
授权列表。添加(“MNO”);
增列授权清单(“PQR”);
增列授权清单(“STU”);
授权列表添加(“VWX”);
增列(简称“YZA”);
JSONObject json=新的JSONObject();
put(“grantList”,grantList);
MvcResult grantAuthzResult=mockMvc.perform(MockMvcRequestBuilders.post(用户URL)
.contentType(contentType)
.param(“用户ID”,用户ID)
.param(“authorities”,json.toString()))
.andExpect(状态().isOk())
.andDo(print())
.andReturn();
}
}
执行时,我的测试会引发非法参数异常:

“没有足够的变量值可用于展开“userId”


我在测试中使用.param()方法发送所需的URL参数,我做错了什么?我提到了这个可能重复的问题,但没有发现它有多大用处

我发现我做错了什么,这里使用param()方法不是正确的方法,因为我的控制器方法中有
@PathVariable
@RequestBody
作为参数

public Collection<UserEntity.UserAuthz> grantAuthz(@PathVariable("userId") String userId,
                                                           @RequestBody ArrayList<String> authorities) {
由于所需的类型是
@RequestBody ArrayList
而不是使用
JSONObject
,因此我使用
JSONArray
并使用content()方法将JSONArray作为字符串发送

以下是我对测试方法所做的更改

   @Test
    public void testGrantAuthorizationForUser() throws Exception{
        Optional<UserEntity> userEntityAuthz = userRepository.findOneByUsername(USER_NAME);
        Set<String> expectedAuthzList = (LinkedHashSet)userEntityAuthz.get().getAuthorizations();

        List<String> grantList = new ArrayList<>();
        grantList.add("ABC");
        grantList.add("DEF");
        grantList.add("GHI");
        grantList.add("JKL");
        grantList.add("MNO");
        grantList.add("PQR");
        grantList.add("STU");
        grantList.add("VWX");
        grantList.add("YZA");

        JSONArray json = new JSONArray();

        MvcResult grantAuthzResult = mockMvc.perform(MockMvcRequestBuilders.post(USER_URL,USER_ID)
                .contentType(contentType)
                .content(json.toString()))
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();
    }
@测试
public void testGrantAuthorizationForUser()引发异常{
可选userEntityAuthz=userRepository.findOneByUsername(用户名);
Set expectedAuthzList=(LinkedHashSet)userEntityAuthz.get().getAuthorizations();
List grantList=new ArrayList();
授权列表。添加(“ABC”);
授权列表。添加(“DEF”);
赠款清单。添加(“GHI”);
授权列表。添加(“JKL”);
授权列表。添加(“MNO”);
增列授权清单(“PQR”);
增列授权清单(“STU”);
授权列表添加(“VWX”);
增列(简称“YZA”);
JSONArray json=新的JSONArray();
MvcResult grantAuthzResult=mockMvc.perform(MockMvcRequestBuilders.post(用户URL、用户ID)
.contentType(contentType)
.content(json.toString())
.andExpect(状态().isOk())
.andDo(print())
.andReturn();
}

这太棒了。帮助了我+从我这里得到1。谢谢
   @Test
    public void testGrantAuthorizationForUser() throws Exception{
        Optional<UserEntity> userEntityAuthz = userRepository.findOneByUsername(USER_NAME);
        Set<String> expectedAuthzList = (LinkedHashSet)userEntityAuthz.get().getAuthorizations();

        List<String> grantList = new ArrayList<>();
        grantList.add("ABC");
        grantList.add("DEF");
        grantList.add("GHI");
        grantList.add("JKL");
        grantList.add("MNO");
        grantList.add("PQR");
        grantList.add("STU");
        grantList.add("VWX");
        grantList.add("YZA");

        JSONArray json = new JSONArray();

        MvcResult grantAuthzResult = mockMvc.perform(MockMvcRequestBuilders.post(USER_URL,USER_ID)
                .contentType(contentType)
                .content(json.toString()))
                .andExpect(status().isOk())
                .andDo(print())
                .andReturn();
    }
        @Test
public void getOneContactAPI() throws Exception {
    String id = "8";
    mvc.perform(MockMvcRequestBuilders.get("/api/contact/{id}",id).accept(MediaType.APPLICATION_JSON))
    .andDo(MockMvcResultHandlers.print())
    .andExpect(status().isOk())
    .andExpect(MockMvcResultMatchers.jsonPath("id").exists());

}