How to test if method returns expected data type?

12,458

Solution 1

Normally, there is no need to test the return type. C# is statically typed language, so this method cannot return something else different than string.

But If you want to write a test, which will fail if someone changes the return type, you can do something like this:

Assert.That(result, Is.TypeOf<string>());

Solution 2

To test for the return type you can use the Is.TypeOf<yourType> syntax mentioned by @dimitar-tsonev. Here is a list of the supported type contraints:

You also mention that you want to write tests to verify the exceptions. For that you can either use the ExpectedExceptionAttribute attribute as documented here or the exception asserts syntax as documented here.

Share:
12,458
Rob Gleeson
Author by

Rob Gleeson

Software Developer from the Bog!

Updated on June 27, 2022

Comments

  • Rob Gleeson
    Rob Gleeson almost 2 years

    Is it possible to create a NUnit Test method to check if the method returns the expected data type ?

    Here's what I mean:

    I've a static string that takes two parameters and checks to see if it matches with another string. If it does the methods simply returns that string.

    I want to test to ensure that this method does infact return type of string and any exceptions that might occur.

    Sample Code:

    public static string GetXmlAttributeValue(this XmlElement element, string attributeName)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
    
            if (attributeName == null)
            {
                throw new ArgumentNullException("attributeName");
            }
    
            string attributeValue = string.Empty;
            if (element.HasAttribute(attributeName))
                attributeValue = element.Attributes[attributeName].Value;
            else
                throw new XmlException(element.LocalName + " does not have an attribute called " + attributeName);
            return attributeValue;
        }
    

    Here's how my solution is looking:

    enter image description here

    I'd like to write my test code within the TestLibrary class library.