在Junit中验证网址的值?

时间:2016-12-07 01:27:55

标签: java json junit

我必须为返回URL的方法编写单元测试用例, 我要验证URL中参数的所有值,是否有任何API或更好的解决方法..

任何建议都将不胜感激。

Java方法:

 class Sample{
      public String returnURL(){
          return "http://localhost:9080/sample?a=12-a&b=param2&c=param3&d=param_4&e=param5"
        }
}

的Junit:

@Test
public void returnURLTest(){
  String url = new Sample().returnURL()
  // Parse the url 
  assert url['a'] == "param1"
 assert url['b'] == "param2"
}

由于

2 个答案:

答案 0 :(得分:3)

如果您使用AssertJ,您可以创建URI(或URL)对象并在其上使用断言,如以下示例所示:https://github.com/joel-costigliola/assertj-examples/blob/master/assertions-examples/src/test/java/org/assertj/examples/UriAssertionsExamples.java

assertThat(new URI("http://www.helloworld.org/index.html?happy=very")).hasParameter("happy", "very");

答案 1 :(得分:1)

您只需要解析网址并比较您提取的各个部分。

类似的东西:

int indexOfNextParameter = url.indexOf("=");
List<String> parameters = new ArrayList<>();

while(youAreParsingTheURL){
    int indexOfParameter = url.indexOf("=", indexOfNextParameter);
    String parameter = url.substring("=", indexOfParameter);
    parameters.add(parameter);
}

然后只需浏览参数列表并验证每个项目。