简体   繁体   中英

Unit testing interface implementations, how to do it?

How to test the behavior of the implementations of interface methods in (abstract) classes without having to copy the tests to each class?

I have (abstract) classes that implement multiple interfaces. I know how each interface should behave, and I define this in test methods so that I don't have to manually repeat these tests for each and every implementation of an interface.

I could create for each interface an abstract class with the tests, and have an abstract method CreateSUT() that creates a new instance of the concrete class. But then I'd have to create a new class with the same CreateSUT() implementation for each interface a class implements, as C# does not support multiple inheritance. Is there a better way to do this?

Also note that I also want to test interfaces implemented in abstract classes that have several non-abstract subclasses, complicating the matter slightly.


This question is not about whether I should unit test my interface implementations. Opinions differ and I've decided to do it because I know how the interface implementations are expected to behave (never returning a null value, returning a read-only collection, etc) and putting these tests together makes it much easier for me to test their implementations, however many there may be.

You could create a list to hold instances of all concrete implementations of your interface, then go through each element in that list and assert the invariant in your test.

Depending on your test framework, there should be a way to get actionable feedback when the test fails.

A quick search found me this for nUnit: http://www.nunit.org/index.php?p=testCaseSource&r=2.5.9

Well, I didn't understand why you need this, but you can write static helper class with tests for your interface. Eg

public static class IFooTests
{
    public static void ShouldDoSomething(this IFoo foo)
    {
        // Assert something
    }
}

Later for every object that implements IFoo interface you can quickly create test methods:

[Test]
public void ShouldDoSomething()
{
    Bar bar = new Bar(); // create and setup your concrete object
    bar.ShouldDoSomething(); // call interface test extension
}

您可以使用moq模拟抽象类,或者创建一个实现所有接口的接口,然后让抽象类实现您新创建的接口,然后模拟新接口。

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