dimanche 28 décembre 2014

Unit testing abstract generic classes

I have a generic abstract class with some methods like:



public abstract class MasterDataViewModel<TPrimaryModel> : ViewModel
where TPrimaryModel : TwoNames, new()
{
public void New()
{
PrimaryModel = new TPrimaryModel();
Address = new Address();
RaisePropertyChanged(String.Empty, validatePropertyName: false);
ViewMode = ViewMode.New;
}

public void Save()
{
...
}
}


This base abstract class is derived a couple of times. I think it's not possible/good to unit test the abstract class directly. My idea was to write an abstract generic unit test class for the class like:



[TestClass]
public abstract class MasterDataViewModelTest<TPrimaryModel>
where TPrimaryModel : TwoNames, new()
{
#region Properties
protected MasterDataViewModel<TPrimaryModel> ViewModel;
#endregion

[TestClass]
public class NewCommand : MasterDataViewModelTest<TPrimaryModel>
{
/// <summary>
/// New command "clears" all content of the viewmodel
/// </summary>
[TestMethod]
public void Execute()
{
//Arrange
TPrimaryModel primaryModel = new TPrimaryModel();

////Fill view model with "random" values
const string name = "Just a string";
ViewModel.SearchTerm = name;
ViewModel.Name1 = name;
ViewModel.Name2 = name;
...

////Set view mode to "random" value
ViewModel.ViewMode = ViewMode.Edit;

//Act
ViewModel.NewCommand.Execute(null);

//Assert
Assert.AreEqual(ViewMode.New, ViewModel.ViewMode);

Assert.IsTrue(String.IsNullOrEmpty(ViewModel.SearchTerm));
Assert.IsTrue(String.IsNullOrEmpty(ViewModel.Name1));
Assert.IsTrue(String.IsNullOrEmpty(ViewModel.Name2));
...
}
}
}


For every derived class of my MasterDataViewModel I could write a unit test class which derives from my abstract unit test class:



[TestClass]
public class RecipientViewModelTest : MasterDataViewModelTest<Recipient>
{

}


By doing so I hoped that this class would "get" all tests from the base unit test class automatically and I could execute those tests.


Is this technically possible? And is this an approach you can recommend? Or are there better approaches?


Aucun commentaire:

Enregistrer un commentaire