Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I have a project implementing Dependency injection using Windsor Castle.
I have to write Unit Test Project for the same.
I'm new to writing Unit test Project Could anyone help in below scenario.
I was able to implement the conventional unit test methods but I'm not able to write test methods for the Dependency Injection implemented in this project.
How can I write test methods for the methods written in a class which have dependency injection used (Windsor Castle is used for Dependency Injection)

Any pointers will be appreciable.
Thanks.
Posted

1 solution

There is a concept known as 'Setup' and 'Teardown' when unit testing.

You can define methods in your test class which have special significance to the test framework (ie. MS Test, NUnit) which is executing your tests. You can use following attributes with MS Test class, which specify code to be run

- before each test is run [TestInitialize]
- after a test has finished running TestCleanup]
- before any tests are run [ClassInitialize]
- after all tests have been executed [ClassCleanup]

I don't use CastleWindsor myself, but your code would look something along following lines ...

C#
namespace MyTestProject
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class MyTestClass
    {
        private static IWindsorContainer _Container;

        [ClassInitialize()]
        public static void ClassInit(TestContext context)
        {
            // create dependency container, and perform registrations for SUT
            var container = new WindsorContainer();
            container.Register(
                Component.For<IObjectToTest>().ImplementedBy<ObjectToTest>()
                );
            _Container = container;
        }

        [TestMethod()]
        public void MyTestMethod()
        {
            IObjectToTest obj = _Container.Resolve<IObjectToTest>(); // arrange
            var result = obj.MyMethod(); // act
            Assert.IsNotNull(obj); // assert
        }

        [ClassCleanup()]
        public static void ClassCleanup()
        {
            _Container.Dispose(); // dispose of container when all tests are complete
        }
    }
}


Hope that helps get you started!
 
Share this answer
 
Comments
sagar wasule 20-Aug-15 8:35am    
Thanks so much, I will take a look into this....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900