1

Context

I've just came across a scenario where I have multiple UnitTests that are similiar enough to be almost handled in a ctrl-c ctrl-v way. For example, when asserting that AutoMapper and its Profiles are valid.

Question

So I've been thinking if it would be considered a good practice to extract an Interface from those tests and implement it whenever I need to test a new Class that falls within the same purpose.

Code Snippet

For example, for the following Tests:

[Fact]
public void ConfigurationValid()
{
    throw new System.NotImplementedException();
}

[Fact]
public void FromCreate()
{
    throw new System.NotImplementedException();
}

[Fact]
public void FromEdit()
{
    throw new System.NotImplementedException();
}

[Fact]
public void ToDetail()
{
    throw new System.NotImplementedException();
}

[Fact]
public void ToList()
{
    throw new System.NotImplementedException();
}

[Fact]
public void ToList_Many()
{
    throw new System.NotImplementedException();
}

Could be extracted to the following interface:

public interface IViewModelsTests
{
    void ConfigurationValid();
    void FromCreate();
    void FromEdit();
    void ToDetail();
    void ToList();
    void ToList_Many();
}

And whenever I create a new ViewModel and wish to unit test it I can just implement the interface on my new TestClass and have it cover all the default scenarios. And I could still have flexibility to add new tests to cover very specific scenarios for each ViewModel, whenever needed.

Alves RC
  • 1,778
  • 14
  • 26
  • For your particular case, AutoMapper could (should) be tested through tests of actual behaviour. – Fabio Sep 28 '19 at 07:53

1 Answers1

3

If they are similar enough, it wouldn't be awful to derive from a base class to run those tests. Then the functionality is written once and added to all implementations.

Just be careful not to make them too complicated, or have multiple levels of inheritance. That can lead to pretty unreadable tests and unmaintainable code.

pete the pagan-gerbil
  • 3,136
  • 2
  • 28
  • 49