[英]How do I Unit test is URL valid in c#?
I have a class that checks to see if the URL is valid using the method below: 我有一个类,使用以下方法检查URL是否有效:
return !string.IsNullOrEmpty(url) &&
Uri.TryCreate(url, UriKind.Absolute, out uriResult) &&
(uriResult.Scheme == Uri.UriSchemeHttp ||
uriResult.Scheme == Uri.UriSchemeHttps);
I was wondering how I would unit test the code to check to see if the URL is valid or not. 我想知道如何对代码进行单元测试,以检查URL是否有效。
So far, i have a unit test that only partially covers the unit test which is below. 到目前为止,我的单元测试仅部分涵盖了下面的单元测试。
string url = "newUrl";
var result = UrlUtility.IsValid(url);
Assert.IsFalse(result);
Any help would be much appreciated. 任何帮助将非常感激。 Thanks
谢谢
You should cover all conditions of IsValid()
method: 您应该涵盖
IsValid()
方法的所有条件:
[TestMethod]
public void TestEmptyUrl()
{
string url = "";
Assert.IsFalse(UrlUtility.IsValid(url));
}
[TestMethod]
public void TestInvalidUrl()
{
string url = "bad url";
Assert.IsFalse(UrlUtility.IsValid(url));
}
[TestMethod]
public void TestRelativeUrl()
{
string url = "/api/Test";
Assert.IsFalse(UrlUtility.IsValid(url));
}
[TestMethod]
public void TestUrlWithInvalidScheme()
{
string url = "htt://localhost:4000/api/Test";
Assert.IsFalse(UrlUtility.IsValid(url));
}
[TestMethod]
public void TestUrlWithHttpScheme()
{
string url = "http://localhost:4000/api/Test";
Assert.IsTrue(UrlUtility.IsValid(url));
}
[TestMethod]
public void TestUrlWithHttpsScheme()
{
string url = "https://localhost:4000/api/Test";
Assert.IsTrue(UrlUtility.IsValid(url));
}
You can give some values for the url. 您可以为网址提供一些值。 For example you can test the next case:
例如,您可以测试下一个案例:
string url = string.Empty;
var result = UrlUtility.IsValid(url);
Assert.IsFalse(result);
Also, you can read about the Uri.UriSchemeHttp and Uri.UriSchemeHttps on the internet and try to make some test to respect or to ignore this uri scheme. 此外,您可以在互联网上阅读有关Uri.UriSchemeHttp和Uri.UriSchemeHttps的信息,并尝试进行一些测试以尊重或忽略此uri方案。 Hope it helps!
希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.