Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Test with Ninject Instantiate

I'm trying to test my service using ninject and an unit test project with visual studio 2012. My inject works ok on my controllers, but when I try to do the same in the unit test class I get an Exception.

System.NullReferenceException: Object reference not set to an instance of an object.

namespace Trex.UnitTests
{
    [TestClass]
    public class GiftServiceTests
    {
        private IGiftService _giftService;

        public void GiftServiceTest(IGiftService giftService)
        {
             _giftService = giftService; 
        }

        [TestMethod]
        public void AddGift()
        {

            var list = _gift.FindAll();  <--- this line throw an exception
        }
    }
}

I think there is something wrong with the injection but I dont get it.

like image 743
Overmachine Avatar asked Jan 08 '13 18:01

Overmachine


1 Answers

The only way dependency injection is able to call your constructor and fill it with a parameter that has a value is if the dependency injection kernel is the one that instantiates your class.

In your case, MSTest is instantiating your test class, so Ninject does not have a chance to call your constructor.

To be honest, you are going about this the wrong way. You will battle MSTest if you pursue this further to try to get Ninject (or any other DI framework) to instantiate your test classes.

I would recommend you use 'new' to instantiate the class under test (_giftService = new GiftService();). If that class has dependencies in its constructor, use a mocking framework to pass in mocked version of those dependencies. This way you isolate your unit tests to only the functionality of the class under test.

like image 62
TylerOhlsen Avatar answered Oct 05 '22 09:10

TylerOhlsen