What should be the strategy of unit testing when using IoC?

后端 未结 4 1762
说谎
说谎 2021-02-12 23:29

After all what I have read about Dependency Injection and IoC I have decided to try to use Windsor Container within our application (it\'s a 50K LOC multi-layer web app, so I ho

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-13 00:09

    You don't need DI container in unit tests because dependencies are provided through mock objects generated with frameworks such as Rhino Mocks or Moq. So for example when you are testing a class that has a dependency on some interface this dependency is usually provided through constructor injection.

    public class SomeClassToTest
    {
        private readonly ISomeDependentObject _dep;
        public SomeClassToTest(ISomeDependentObject dep)
        {
            _dep = dep;
        }
    
        public int SomeMethodToTest()
        {
            return _dep.Method1() + _dep.Method2();
        }
    }
    

    In your application you will use a DI framework to pass some real implementation of ISomeDependentObject in the constructor which could itself have dependencies on other objects while in a unit test you create a mock object because you only want to test this class in isolation. Example with Rhino Mocks:

    [TestMethod]
    public void SomeClassToTest_SomeMethodToTest()
    {
        // arrange
        var depStub = MockRepository.CreateStub();
        var sut = new SomeClassToTest(depStub);
        depStub.Stub(x => x.Method1()).Return(1);
        depStub.Stub(x => x.Method2()).Return(2);
    
        // act
        var actual = sut.SomeMethodToTest();
    
        // assert
        Assert.AreEqual(3, actual);
    }
    

提交回复
热议问题