How to unit test a method that uses a dependency to copy an object? - unit-testing

Consider the following code (in C# but it could be any other language):
public interface IObjectCopier
{
void Copy<T>(T source, T target);
}
public class Model
{
public string Name { get; set; }
}
public class ViewModel
{
private readonly IObjectCopier _objectCopier;
public ViewModel(IObjectCopier objectCopier)
{
_objectCopier = objectCopier;
}
public Model ViewBindData { get; set; }
public void Load(Model model)
{
_objectCopier.Copy(model, ViewBindData);
}
}
How do I construct a unit test for the Load method? If I mock IObjectCopier then I need to supply a mock implementation of the Copy method. In this example it is trivial but in a real world scenario Model can be large with sub models and the mocking exercise feel like it is just copying what the IObjectCopier implementation does.
The problem is simplified if I could change the Copy method to the following:
T Copy<T>(T source);
As in this case the mock setup is drastically simplified. The problem is that there are view bindings to the Model object and I cannot simply destroy and re-create the object.
Is there an elegant way to get around this problem?

If you're using mocks, then the only thing you care about is that the copier is invoked with the 2 parameters.
So in some sort of pseudo code
test "populates model from view data" {
objectCopiermock = mock(IObjectCopier)
model = new Model() //create empty or use a TestDataBuilder
viewBindData = new viewBindData() //create empty or use a TestDataBuilder
viewModel = new ViewModel(objectCopiermock)
viewModel.viewBindData(viewBindData)
viewModel.Load(model)
verifyMock(objectCopiermock).copy(model, viewBindData)
}
The important thing with mocks is to verify the interactions, and not the values inside model or viewBindData.
If this is confused, don't panic! (tm) - and I would suggest you to read a bit about the difference between the London and Chicaco/Detroit schools of TDD

Related

Unit Testing BLL: mock Repository, UnitOfWork, UnitOfWorkFactory

I need a jump start in testing the methods on my Business layer. Consider the Materials BLL object, how can I test the AddNewMaterial method for it?
interface IGenericRepository<TEntity>
{
TEntity Add(TEntity m);
}
public interface IMaterialRepository : IGenericRepository<Material>
{
}
public interface IUnitOfWork
{
IMaterialRepository Materials { get; private set;}
void Save();
}
public interface IUnitOfWorkFactory
{
IUnitOfWork GetUnitOfWOrk();
}
public class MaterialsBLL
{
private readonly IUnitOfWorkFactory _uowFactory;
//uowFactory comes from DI
public MaterialsBLL(IUnitOfWorkFactory uowFactory)
{
_uowFactory = uowFactory;
}
//TODO: test this
public Material AddNewMaterial(Material m)
{
using(var uow = _uowFactory.GetUnitOfWOrk())
{
var result = uow.Materials.Add(m);
uow.Save();
return result;
}
}
I am using Moq, and XUnit, but am very green. In general I want to do this:
Mock the repositories Add method.
Mock the UoW Materials property to return my repository mock.
Mock the UoWFactory to return the UoW mock.
Create the MaterialsBLL giving the mocked UoWFactory to the contstructor.
Verify that the AddNewMaterials calls the repository's Add, and the UoW's Save, etc.
It seems to me that, I maybe should be creating a Fake MaterialRepository, rather than mocking it? Any other advice? Here is a first crack:
[Fact]
public void TestGetMaterialById()
{
var materialList = GetMaterials();
var materialRepositoryMock = new Mock<IMaterialRepository>();
materialRepositoryMock.Setup(repo => repo.Get(4)).Returns(materialList.First());
var uowMock = new Mock<IUnitOfWork>();
uowMock.SetupProperty<IMaterialRepository>(uow => uow.Materials, materialRepositoryMock.Object);
var uowFactoryMock = new Mock<IUnitOfWorkFactory>();
uowFactoryMock.Setup(f => f.GetUnitOfWork()).Returns(uowMock.Object);
var materialsBll = new Materials(uowFactoryMock.Object);
var result = materialsBll.Get(4);
Assert.Equal(result.MaterialId, 4);
Assert.Equal(result.Name, "Four");
}
When you feel like you need several levels of nested mock objects, there's generally something wrong with your design.
The Law of Demeter warns us here that you should probably not tinker with uow.Materials in MaterialsBLL.
Besides, a Unit of Work is typically not the place to expose Repositories. The code that needs to access Materials will usually have a direct reference to an IMaterialsRepository, not ask it from the UoW, and then the Repository implementation might reference the UoW internally.
This leads to a flatter design and simplifies your production code as well as your tests.

Castle Windsor: unit test component lifecycle

I would like to write a non-regression test to validate that transient components are well released. Some are created by a direct injection in ctor, other by typed factories.
I thought that I could do this way:
// Given
var rootComponent = container.Resolve<IRootComponent>();
var c1 = rootComponent.C1;
var c2 = c1.C2;
etc.
Assert.True(Container.Kernel.ReleasePolicy.HasTrack(c1));
Assert.True(Container.Kernel.ReleasePolicy.HasTrack(c2));
// When
c1.Close();
// Then
Assert.False(Container.Kernel.ReleasePolicy.HasTrack(c1));
Assert.False(Container.Kernel.ReleasePolicy.HasTrack(c2));
HasTrack() always returns false, although if I look at the container in debug mode, I can see my components well tracked. Why is that? Do you have any suggestion for such a test?
Thx for your help
The reason that your components are not tracked is that the component and it's dependencies have no decomissioning requirements. In this case there is no reason for windsor to track them.
When using windsor in general you should only resolve on your container once to obtain your top level component. All other component are either injected or created by a factory. There is no need to worry about the live time of injected components. The container will handle it for you.
For transient components that you create with a factory you should be aware that they will never live (be tracked) longer then the factory it self. So if you don't mind that your components live at long as your factory there is no need to release them (using a destroy method on a factory).
For component that I want to make sure that I release them, I generally I create unit test for which I stub out the factory. That way it is easy to test that destroy is called.
I think with the approach that you are taking you are not just testing your code but also the container. IMHO windsor is already well tested, and test should focus on your own code.
Good luck,
Marwijn.
Two years too late, but here's a test.
public class DependsOnSomethingDisposable
{
private readonly SomethingDisposable _disposable;
public Boolean SomethingDisposableIsDisposed { get { return _disposable.Disposed; } }
public DependsOnSomethingDisposable(SomethingDisposable disposable)
{
_disposable = disposable;
}
}
public class SomethingDisposable : IDisposable
{
public Boolean Disposed { get; private set; }
public void Dispose()
{
Disposed = true;
}
}
[TestClass]
public class WindsorLifestyleTests
{
private IWindsorContainer _container;
[TestInitialize]
public void Setup()
{
_container = new WindsorContainer();
}
[TestCleanup]
public void Cleanup()
{
_container.Dispose();
}
[TestMethod]
public void TransientDependencyIsDisposed()
{
_container.Register(
Component.For<DependsOnSomethingDisposable>().LifestyleTransient(),
Component.For<SomethingDisposable>().LifestyleTransient()
);
var resolved = _container.Resolve<DependsOnSomethingDisposable>();
_container.Release(resolved);
Assert.IsTrue(resolved.SomethingDisposableIsDisposed);
}
[TestMethod]
public void NonTransientDependencyIsNotDisposed()
{
_container.Register(
Component.For<DependsOnSomethingDisposable>().LifestyleTransient(),
Component.For<SomethingDisposable>().LifestyleSingleton()
);
var resolved = _container.Resolve<DependsOnSomethingDisposable>();
_container.Release(resolved);
Assert.IsFalse(resolved.SomethingDisposableIsDisposed);
}
}

Moq - how to verify method call which parameter has been cleaned (a list)

I've got the following code and I need help to write a unit test for it. I'm using Moq library.
Here's the deal. I have a business class with a dependency to a repository (interface), so I can use it to save my entities to the database. My entity is basically a list of strings. The method AddAndSave, from MyBusinessClass, grab the value it receives as a parameters, put it into the list and call Save method from IRepository. Then, I clear the list of my entity. The code below show this example (I've made it simple so I can explain it here).
There's a unit test, too.
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
namespace TestesGerais
{
public class MyEntity
{
public MyEntity()
{
MyList = new List<string>();
}
public List<string> MyList { get; set; }
}
public interface IRepository
{
void Save(MyEntity entity);
}
public class MyBusinessClass
{
public IRepository Repository { get; set; }
private MyEntity _entity = new MyEntity();
public void AddAndSave(string info)
{
_entity.MyList.Add(info);
Repository.Save(_entity);
_entity.MyList.Clear(); // for some reason I need to clear it
}
}
[TestClass]
public class UnitTest10
{
[TestMethod]
public void TestMethod1()
{
var mock = new Mock<IRepository>();
MyBusinessClass b = new MyBusinessClass() { Repository = mock.Object };
b.AddAndSave("xpto");
mock.Verify(m => m.Save(It.Is<MyEntity>(x => x.MyList[0] == "xpto")), Times.Exactly(1));
}
}
}
My unit-test check if the IRepository's Save method was called with its parameter (an entity) having one element in the list, and having the value "xpto" in this element.
When I run this test, it turns red with the error message "Test method TestesGerais.UnitTest10.TestMethod1 threw exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index".
Ok, this is caused by the list that has been cleaned. If I comment the line "_entity.MyList.Clear();", everything goes well.
My question is: how can I test this without commenting the "Clear" line in my business class, and making sure that my repository's method is called passing the specific value (entity with one element with value "xpto")?
Thanks
I've changed my unit test using the Callback feature of Moq. This way, I can setup the mock so when AddAndSave is called, the parameter it receives is saved into a variable from my unit test, and I can assert it later.
[TestMethod]
public void TestMethod1()
{
var mock = new Mock<IRepository>();
string result = string.Empty;
mock.Setup(m => m.Save(It.IsAny<MyEntity>())).Callback((MyEntity e) => { result = e.MyList[0]; });
MyBusinessClass b = new MyBusinessClass() { Repository = mock.Object };
b.AddAndSave("xpto");
Assert.AreEqual(result, "xpto");
}
You could split your method up a bit. "AddAndSave" isn't all it does. You could then just test the behaviour of the adding and saving bit in isolation.

How to mock HttpClientCertificate?

I am trying to unit test an action filter I wrote. I want to mock the HttpClientCertificate but when I use MOQ I get exception. HttpClientCertificate doesnt have a public default constructor.
code:
//Stub HttpClientCertificate </br>
var certMock = new Mock<HttpClientCertificate>();
HttpClientCertificate clientCertificate = certMock.Object;
requestMock.Setup(b => b.ClientCertificate).Returns(clientCertificate);
certMock.Setup(b => b.Certificate).Returns(new Byte[] { });
This is the most awkward case of creating unit testable systems in .NET. I invariable end up adding a layer of abstraction over the component that I can't mock. Normally this is required for classes with inaccessible constructors (like this case), non-virtual methods or extension methods.
Here is the pattern I use (which I think is Adapter pattern) and is similar to what MVC team has done with all the RequestBase/ResponseBase classes to make them unit testable.
//Here is the original HttpClientCertificate class
//Not actual class, rather generated from metadata in Visual Studio
public class HttpClientCertificate : NameValueCollection {
public byte[] BinaryIssuer { get; }
public int CertEncoding { get; }
//other methods
//...
}
public class HttpClientCertificateBase {
private HttpClientCertificate m_cert;
public HttpClientCertificateBase(HttpClientCertificate cert) {
m_cert = cert;
}
public virtual byte[] BinaryIssuer { get{return m_cert.BinaryIssuer;} }
public virtual int CertEncoding { get{return m_cert.CertEncoding;} }
//other methods
//...
}
public class TestClass {
[TestMethod]
public void Test() {
//we can pass null as constructor argument, since the mocked class will never use it and mock methods will be called instead
var certMock = new Mock<HttpClientCertificate>(null);
certMock.Setup(cert=>cert.BinaryIssuer).Returns(new byte[1]);
}
}
In your code that uses HttpClientCertificate you instead use HttpClientCertificateBase, which you can instantiate like this - new HttpClientCertificateBase(httpClientCertificateInstance). This way you are creating a test surface for you to plug in mock objects.
The issue is that you need to specify constructor parameters when creating the mock of the HttpClientCertificate.
var certMock = new Mock<HttpClientCertificate>(ctorArgument);
The bad news is that the ctor for HttpClientCertificate is internal and takes in an HttpContext, so it probably won't work.
Unless you want to write more code to make the class "Testable" I suggest you use Typemock Isolator, Unless specified otherwise it looks for the first c'tor available - public, internal or private and fake (mocks) it's parameters so you won't have to.
Creating the fake object is as simple as:
var fakeHttpClientCertificate = Isolate.Fake.Instance<HttpClientCertificate>();
Another alternative is to use the free Microsoft Moles framework. It will allow you to replace any .NET method with your own delegate. Check out the link as it gives an example that is pretty easy to understand. I think you'll find it much nicer than adding layers of indirection to get HttpClientCertificate into a testable state.

Create System.Data.Linq.Table in Code for Testing

I have an adapter class for Linq-to-Sql:
public interface IAdapter : IDisposable
{
Table<Data.User> Activities { get; }
}
Data.User is an object defined by Linq-to-Sql pointing to the User table in persistence.
The implementation for this is as follows:
public class Adapter : IAdapter
{
private readonly SecretDataContext _context = new SecretDataContext();
public void Dispose()
{
_context.Dispose();
}
public Table<Data.User> Users
{
get { return _context.Users; }
}
}
This makes mocking the persistence layer easy in unit testing, as I can just return whatever collection of data I want for Users (Rhino.Mocks):
Expect.Call(_adapter.Users).Return(users);
The problem is that I cannot create the object 'users' since the constructors are not accessible and the class Table is sealed. One option I tried is to just make IAdapter return IEnumerable or IQueryable, but the problem there is that I then do not have access to the methods ITable provides (e.g. InsertOnSubmit()). Is there a way I can create the fake Table in the unit test scenario so that I may be a happy TDD developer?
My current solution is to wrap the functionality I want from Table into a TableWrapper class:
public interface ITableWrapper<TEntity>
where TEntity : class
{
IEnumerable<TEntity> Collection { get; }
void InsertOnSubmit(TEntity entity);
}
And here's the implementation:
public class TableWrapper<TEntity> : ITableWrapper<TEntity>
where TEntity : class
{
private readonly Table<TEntity> _table;
public TableWrapper(Table<TEntity> table)
{
_table = table;
}
public IEnumerable<TEntity> Collection
{
get { return _table; }
}
public void InsertOnSubmit(TEntity entity)
{
_table.InsertOnSubmit(entity);
}
}
So now I can easily mock data from Collection, as well as keeping the functionality of InsertOnSubmit (any other functions that I need down the road can be added later on).
I have had success using the Data Access Layer to produce domain object collections and then using linq to objects.
The object under test then only relates to List, which is fairly easy to unit test.
I don't like when the logic entities should have Data Access Layer dependencies. They should stop at the service layer, if even there. I usually go for the model where the service layer invokes a data access object to get a List, passes that list into whichever logic object that needs it (if necessary uses linq-to-objects to filter out the relevant data and injects it into eiter a flat list, dictionary or an object model).
The business objects become very testable, even though they don't benefit from the richness of the inferred data model.