Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# unit test override method [closed]

I am relatively new to Unit testing and I was wondering if there is a built in solution for the following problem.

I want to test a method which at one point measures some input from a hardware.

var results = Measurement.MeasureAll();

I want of course to test this without the hardware. Is there a way to override somehow for the scope of the unit test the Measurement.MeasureAll(); method to return some predefined values?

like image 474
Tamaska Janos Avatar asked Sep 09 '26 17:09

Tamaska Janos


1 Answers

You would mock the dependency. This is your dependency:

Measurement

What is Measurement? Where does it come from? In order to make the code unit-testable, Measurement should be supplied to that code. Something like this:

public void MethodBeingTested(Measurement measurement)
{
    // use Measurement here
}

Or maybe this:

public class SomeClass
{
    private Measurement TheMeasurement { get; set; }

    public SomeClass(Measurement theMeasurement)
    {
        TheMeasurement = theMeasurement;
    }

    public void MethodBeingTested()
    {
        // use TheMeasurement here
    }
}

Then your unit tests can create a fake/mock/stub/etc. Measurement and supply that to the tests. (There are tons of mocking libraries available to help with this. I personally like Moq and RhinoMocks.) That "mock" version would be defined by the tests to perform in a specific and predictable way. It would then observe that the code being tested interacted with the mock in exactly the way that was expected.


Now, some objects are notoriously difficult to mock. This can especially be the case if what you're showing us is static. (Static members make unit tests notoriously difficult.) This is where you would wrap such an object in a mockable wrapper which can be mocked. Something as simple as this:

public interface IMeasurement
{
    SomeType MeasureAll();
}

public class MyMeasurement
{
    // declare Measurement here?  some other context?

    public SomeType MeasureAll()
    {
        return Measurement.MeasureAll();
    }
}

The idea here is that your business logic would couple to IMeasurement, over which you have complete control and mockability/testability. Then you could supply a mocked version of the wrapper class (made trivial by the use of an interface) and not have to worry about mocking the actual dependency.

like image 62
David Avatar answered Sep 12 '26 06:09

David



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!