Reputation: 67
I am presently working on a project that has methods which have as parameters, complicated objects (mostly Repository objects). The testing has to be done using MSTest. Would it be a wise approach to have the objects created in the TestInitialize method, so that they could be used as arguments in the used for passing as parameters to the Actual Method in the test method? Please suggest better alternatives.
I am attaching sample code of the Method that needs to be unit tested(Exectue() method) underneath
public class AddOrdersToDbCommand
{
private IOrdersRepository _ordersRepository;
private OrderSetting _ordersSetting;
public AddOrdersToDbCommand(IOrdersRepository ordersRepository, OrderSetting ordersSetting)
{
_ordersRepository = ordersRepository;
_ordersSetting = ordersSetting;
}
public void Execute()
{
OrderSetting modifyOrderSettings = _ordersRepository.Get(_ordersSetting.Id);
modifyOrderSettings.Name = _ordersSetting.Name;
modifyOrderSettings.Status = _ordersSetting.Status;
modifyOrderSettings.UpdatedBy = _ordersSetting.UpdatedBy;
modifyOrderSettings.UpdatedDate = _ordersSetting.UpdatedDate;
_ordersRepository.SaveOrUpdate(modifyOrderSettings);
_ordersRepository.DbContext.CommitChanges();
}
}
Upvotes: 1
Views: 1184
Reputation: 5293
You should be using Mocks (use a Mocking framework like Moq) to supply any dependent objects. This way you will only be isolating and testing only what is is currently under test.
If you really must create stub objects, I prefer to do it with a helper class. I have TestDataGenerator.cs class. In there you can have a set of static methods for generating objects.
Example usage then would become TestDataGenerator.GetStubOrderSetting();
the advantage of using a util class is that you can create a whole heap of helper methods that return stub objects without making your TestInitialize method huge and slow. Also, you can compose the individual stub methods to return more complicated objects.
For example TestDataGenerator.GetStubEmployeeWithOrder();
will create a stub employee first and then call the TestDataGenerator.GetStubOrderSetting();
that you've already created to set the orders for the newly created stub employee before returning it.
Upvotes: 3
Reputation: 19881
I use a class in testing that sets up a mock (Moq) repository along with setup methods for configuration.
class MockRepo {
private Mock<IRepository> descriptiveSettingRepository;
private ArrayList _repository = new ArrayList();
public MockRepo() {
mockRepo.Setup( /* setup properties */ );
}
}
Use MoQ Callback to add an object to ArrayList. You can also query the ArrayList and return objects.
Upvotes: 0