Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

We're working on an API for some hardware and I'm trying to write some tests for it in C#. try-catch blocks for repetitive tasks were making my code bloated and repetitive so for getters I was able to 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 query the hardware for some known value and compare. I can call with:

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

Which works quite well. But I'm not sure how to do the same with setters. Ie to ensure that the API actually set a value (and doesn't timeout or whatever when I try to set). I'd like to pass the setter to the test method and invoke it in there.

Bonus question: Is there a way to do this with a generic type? There are some custom types defined in the API and I'm not sure of a good way to write these test wrappers for them without writing a new overloaded method for every type. Thanks for any and all help!

like image 652
Gemini Avatar asked Dec 03 '25 11:12

Gemini


1 Answers

You could pass the getter and the setter to the function:

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 the value, then gets it and compares to the value passed to the setter.

You'd have to call it like:

TestSetter(() => myAPI.Firmware.Version, v => myAPI.Firmware.Version = v, 24);
like image 84
Reed Copsey Avatar answered Dec 04 '25 23:12

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!