Reputation: 83
I have a class that checks to see if the URL is valid using the method below:
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.
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
Upvotes: 1
Views: 3738
Reputation: 12201
You should cover all conditions of IsValid()
method:
[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));
}
Upvotes: 3
Reputation: 79
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. Hope it helps!
Upvotes: 0