Using a setter as a parameter in C #? (Maybe with a delegate?)

We are working on an API for some hardware and I am trying to write some tests for it in C #. try-catch blocks for repetitive tasks made my code bloat and repetitive, so for getters I could wrap like this:

TestGetter(Func<int> method, double expectedVal)
{
    int testMe = 0;
    try
    {
        testMe = method();
        PassIfTrue(testMe == expectedVal);
    }
    catch (Exception e)
    {
         Fail(e.Message);
    }
}

      

So, I am querying hardware for some known value and comparison. I can call with:

TestGetter( () => myAPI.Firmware.Version, 24); //Or whatever.

      

It works well. But I'm not sure how to do the same with setters. That is, for the API to actually set the value (and not timeout or whatever when I try to set). I would like to pass the installer to a test method and call it there.

Bonus question: is there a way to do this with a generic type? There are certain custom types in the API, and I'm not sure of a good way to write these test wrappers for them without creating a new overloaded method for each type. Thanks for any help!

+3


source to share


2 answers


You can pass a function to both the receiver and the setter:

void TestSetter<T>(Func<T> getter, Action<T> setter, T value)
{
    try
    {
        setter(value);
        PassIfTrue(EqualityComparer<T>.Default.Equals(getter(), value));
    }
    catch (Exception e)
    {
         Fail(e.Message);
    }       
}

      

This sets a value, then gets it and compared to the value passed to the installer.



You will have to call it like this:

TestSetter(() => myAPI.Firmware.Version, v => myAPI.Firmware.Version = v, 24);

      

+2


source


You can make them generic like Reeds, but you need to use different comparison methods:

    public static void TestGetter<T>(Func<T> method, T expectedVal)
    {       
        try
        {
            T actual = method();
            PassIfTrue(expectedVal.Equals(actual));
        }
        catch (Exception ex)
        {
            Fail(ex.Message);
        }
    }

    public static void TestSetter<T>(Action setMethod, Func<T> getMethod, T expectedVal)
    {
        try
        {
            setMethod();
            T actual = getMethod();
            PassIfTrue(expectedVal.Equals(actual));
        }
        catch (Exception ex)
        {
            Fail(ex.Message);
        }
    }

      



You can also pass a Comparer action to check them if you don't think the method Equals

will work for the expected types.

+1


source







All Articles