Search code examples
c#unit-testingunity-containerrhino-mocks

Unit Testing For Dependey Attributes in Unity


I am currently using Unity, Rhinomocks, MVC4, MS Test.

Is it possible to unit test a class that uses dependency attributes such as the following?

`

public class MyClass
{
 [Dependency]
 public IMyInterface MyObject { get; set; }
}

`
Or is constructor injection the only viable approach?


Solution

  • Why do you want to use the DependencyResolver within a unit test?

    If you want to test MyClass with a real IMyInterface implementation eg

    MyClass instance = new MyClass
    {
        // instantiate MyObject
    }
    

    or if you want to mock MyObject, use RhinoMocks:

    var mocks= new MockRepository();
    MyClass instance = new MyClass
    {
        MyObject = mocks.DynamicMock<IMyInterface>();
    } 
    

    A DynamicMock is a Stub that will return default values unless you set up expectations. Or you can use a StrictMock that will throw an exception if it is used in any way for which no Expectation is set up. Have a look at this article