URL验证程序测试

时间:2017-11-10 12:22:05

标签: c# regex unit-testing validation testing

我们正在为我们的URL验证方法编写单元测试,我们不确定我们是否正在测试正确的案例,所以这基本上是第一个问题; www.google实际上应该返回false,还是实际上是链接的可接受URL?

我们提出了以下案例,以及他们的预期结果,对那些未通过考试的案例发表了评论:

[TestCase("http://www.google.com",true)]
[TestCase("https://www.google.com",true)]
[TestCase("www.google.com",true)]
[TestCase("http://google.com",true)]
[TestCase("google.com",true)]
[TestCase("http://www.google.co.uk", true)] //Fails, returns false
[TestCase("htp://www.google.com",false)]
[TestCase("http://www.google.dk", true)]
[TestCase("http://www.google", false)] 
[TestCase("http://google", false)]
[TestCase("wwww.google.com", false)] 
[TestCase("www.google", false)]
[TestCase("google", false)]

目前正在C#中使用此方法:

public bool IsTargetLinkValid(string targetLink)
{
  if (!targetLink.StartsWith("http://") && !targetLink.StartsWith("https://"))
    targetLink = "http://" + targetLink;

  return Regex.IsMatch(targetLink, @"^(http|http(s)?:\/\/)?(w{3})?\.?[\w-]+?(\.com|\.in|\.org|\.dk)");
}

将http作为if语句的一部分附加不会改变测试结果。

第一: 那些测试用例是否正确?有些不必要吗?

第二: 假设它们是正确的,我们如何让最后三个通过?

还应注意,不应测试特定的顶级域名;西班牙语或德语域名也应该没问题,如果只是添加到正则表达式,添加对所有顶级域名的检查似乎......详尽无遗

请注意,这些网址最终应该用于来自广告的链接,在封闭系统中(但仍可在国际上访问)

3 个答案:

答案 0 :(得分:1)

我认为您可以使用此正则表达式^(http|http(s)?:\/\/)?(w{3})?\.?[\w-]+(\.com|\.in|\.org|\.dk)$

  • 从字符串^
  • 的开头
  • 可选协议(http|http(s)?:\/\/)?
  • 可选www (w{3})?
  • 可选点\.?
  • 一个或多个单词字符/连字符[\w-]+
  • (\.com|\.in|\.org|\.dk)$
  • 结尾

答案 1 :(得分:0)

第三个wwww.google.com返回true,因为您在方法中自动附加http:// - 前缀。

答案 2 :(得分:0)

好的,所以@Thefourthbird提供了一些更好的正则表达式,但最终,第一个问题是重要的问题。我们与一位经验丰富的开发人员进行了交谈,他们基本上说过“不要检查顶级域名,有太多"”这就是我们正在做的事情。

目前的案例是:

[TestCase("http://www.google.com",true)]
[TestCase("https://www.google.com",true)]
[TestCase("www.google.com",true)]
[TestCase("http://google.com",true)]
[TestCase("google.com",true)]
[TestCase("htp://www.google.com",false)]
[TestCase("http://www.google.co.uk", true)]
[TestCase("http://www.google.dk", true)]
[TestCase("http://www.google", true)]
[TestCase("http://google", false)]
[TestCase("wwww.google.com", true)]
[TestCase("www.google", true)]
[TestCase("google", false)]

他们都通过了这个正则表达式^(http|http(s)?://)?([\w-]+.)+[\w-]+[.com|.in|.org]+([\?%&=]*)?

......来自@fourth的灵感。