简体   繁体   中英

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:

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

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));
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM