IOC in UnitTest class - Unity.WebApi












1















I have implemented Unity.WebAPI in web api project successfully. Some how new instance of MService class is not being created. I get following error message when i run unit test method.




Unable to get default constructor for class MServiceTests.




Service Class



    private readonly IRepository _mRepository;

public MService(IMRepository mRepository)
{
_mRepository = mRepository;
}

public List<FUser> GetFUser()
{
result = _mRepository.ExecuteCommandReader()
}


Test Class



 public class MServiceTests
{
private readonly IMRepository _mRepository;
private readonly IMService _mService;


public MServiceTests(IMRepository mRepository, IMService mService)
{
_mRepository = mRepository;
_mService = mService;
}




[TestMethod]
public void Get_Users_ReturnsUserList()
{

var resultList = new List<FUser>();
resultList = _mService.GetFUser();

Assert.IsTrue(resultList.Count > 0);

}
}


UnityConfig



    container.RegisterType<IFService, FService>(new HierarchicalLifetimeManager());
container.RegisterType<IMService, MService>(new HierarchicalLifetimeManager());
container.RegisterType<ITransactionService, TransactionService>(new HierarchicalLifetimeManager());
container.RegisterType<IMRepository, MRepository>();









share|improve this question

























  • What do you mean by "it is not working"?

    – Nkosi
    Nov 15 '18 at 14:54











  • i have updated the question

    – user1263981
    Nov 15 '18 at 14:58











  • And that error happens when and how?

    – Nkosi
    Nov 15 '18 at 14:59











  • do i need to register MServiceTests class type?

    – user1263981
    Nov 15 '18 at 14:59











  • Any thing being resolved from the container has to have been registered first

    – Nkosi
    Nov 15 '18 at 14:59
















1















I have implemented Unity.WebAPI in web api project successfully. Some how new instance of MService class is not being created. I get following error message when i run unit test method.




Unable to get default constructor for class MServiceTests.




Service Class



    private readonly IRepository _mRepository;

public MService(IMRepository mRepository)
{
_mRepository = mRepository;
}

public List<FUser> GetFUser()
{
result = _mRepository.ExecuteCommandReader()
}


Test Class



 public class MServiceTests
{
private readonly IMRepository _mRepository;
private readonly IMService _mService;


public MServiceTests(IMRepository mRepository, IMService mService)
{
_mRepository = mRepository;
_mService = mService;
}




[TestMethod]
public void Get_Users_ReturnsUserList()
{

var resultList = new List<FUser>();
resultList = _mService.GetFUser();

Assert.IsTrue(resultList.Count > 0);

}
}


UnityConfig



    container.RegisterType<IFService, FService>(new HierarchicalLifetimeManager());
container.RegisterType<IMService, MService>(new HierarchicalLifetimeManager());
container.RegisterType<ITransactionService, TransactionService>(new HierarchicalLifetimeManager());
container.RegisterType<IMRepository, MRepository>();









share|improve this question

























  • What do you mean by "it is not working"?

    – Nkosi
    Nov 15 '18 at 14:54











  • i have updated the question

    – user1263981
    Nov 15 '18 at 14:58











  • And that error happens when and how?

    – Nkosi
    Nov 15 '18 at 14:59











  • do i need to register MServiceTests class type?

    – user1263981
    Nov 15 '18 at 14:59











  • Any thing being resolved from the container has to have been registered first

    – Nkosi
    Nov 15 '18 at 14:59














1












1








1


0






I have implemented Unity.WebAPI in web api project successfully. Some how new instance of MService class is not being created. I get following error message when i run unit test method.




Unable to get default constructor for class MServiceTests.




Service Class



    private readonly IRepository _mRepository;

public MService(IMRepository mRepository)
{
_mRepository = mRepository;
}

public List<FUser> GetFUser()
{
result = _mRepository.ExecuteCommandReader()
}


Test Class



 public class MServiceTests
{
private readonly IMRepository _mRepository;
private readonly IMService _mService;


public MServiceTests(IMRepository mRepository, IMService mService)
{
_mRepository = mRepository;
_mService = mService;
}




[TestMethod]
public void Get_Users_ReturnsUserList()
{

var resultList = new List<FUser>();
resultList = _mService.GetFUser();

Assert.IsTrue(resultList.Count > 0);

}
}


UnityConfig



    container.RegisterType<IFService, FService>(new HierarchicalLifetimeManager());
container.RegisterType<IMService, MService>(new HierarchicalLifetimeManager());
container.RegisterType<ITransactionService, TransactionService>(new HierarchicalLifetimeManager());
container.RegisterType<IMRepository, MRepository>();









share|improve this question
















I have implemented Unity.WebAPI in web api project successfully. Some how new instance of MService class is not being created. I get following error message when i run unit test method.




Unable to get default constructor for class MServiceTests.




Service Class



    private readonly IRepository _mRepository;

public MService(IMRepository mRepository)
{
_mRepository = mRepository;
}

public List<FUser> GetFUser()
{
result = _mRepository.ExecuteCommandReader()
}


Test Class



 public class MServiceTests
{
private readonly IMRepository _mRepository;
private readonly IMService _mService;


public MServiceTests(IMRepository mRepository, IMService mService)
{
_mRepository = mRepository;
_mService = mService;
}




[TestMethod]
public void Get_Users_ReturnsUserList()
{

var resultList = new List<FUser>();
resultList = _mService.GetFUser();

Assert.IsTrue(resultList.Count > 0);

}
}


UnityConfig



    container.RegisterType<IFService, FService>(new HierarchicalLifetimeManager());
container.RegisterType<IMService, MService>(new HierarchicalLifetimeManager());
container.RegisterType<ITransactionService, TransactionService>(new HierarchicalLifetimeManager());
container.RegisterType<IMRepository, MRepository>();






c# unit-testing asp.net-web-api inversion-of-control






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 15:13







user1263981

















asked Nov 15 '18 at 14:52









user1263981user1263981

1,20263066




1,20263066













  • What do you mean by "it is not working"?

    – Nkosi
    Nov 15 '18 at 14:54











  • i have updated the question

    – user1263981
    Nov 15 '18 at 14:58











  • And that error happens when and how?

    – Nkosi
    Nov 15 '18 at 14:59











  • do i need to register MServiceTests class type?

    – user1263981
    Nov 15 '18 at 14:59











  • Any thing being resolved from the container has to have been registered first

    – Nkosi
    Nov 15 '18 at 14:59



















  • What do you mean by "it is not working"?

    – Nkosi
    Nov 15 '18 at 14:54











  • i have updated the question

    – user1263981
    Nov 15 '18 at 14:58











  • And that error happens when and how?

    – Nkosi
    Nov 15 '18 at 14:59











  • do i need to register MServiceTests class type?

    – user1263981
    Nov 15 '18 at 14:59











  • Any thing being resolved from the container has to have been registered first

    – Nkosi
    Nov 15 '18 at 14:59

















What do you mean by "it is not working"?

– Nkosi
Nov 15 '18 at 14:54





What do you mean by "it is not working"?

– Nkosi
Nov 15 '18 at 14:54













i have updated the question

– user1263981
Nov 15 '18 at 14:58





i have updated the question

– user1263981
Nov 15 '18 at 14:58













And that error happens when and how?

– Nkosi
Nov 15 '18 at 14:59





And that error happens when and how?

– Nkosi
Nov 15 '18 at 14:59













do i need to register MServiceTests class type?

– user1263981
Nov 15 '18 at 14:59





do i need to register MServiceTests class type?

– user1263981
Nov 15 '18 at 14:59













Any thing being resolved from the container has to have been registered first

– Nkosi
Nov 15 '18 at 14:59





Any thing being resolved from the container has to have been registered first

– Nkosi
Nov 15 '18 at 14:59












2 Answers
2






active

oldest

votes


















2














There seems to be a bit of confusion about how to unit test a class that has dependencies.



Let us assume the subject under test looks like this



public class MService: IMService {

private readonly IMRepository mRepository;

public MService(IMRepository mRepository) {
this.mRepository = mRepository;
}

public List<FUser> GetFUser() {
var result = mRepository.ExecuteCommandReader();
return result
}
}


In order to test the MService.GetFUser you would create an instance of the subject class MService and inject what ever dependencies are needed to test the behavior of the method under test.



In the following example test, the dependencies will be mocked using Moq mocking framework. You could just as easily create a fake implementation if so desired.



[TestClass]
public class MServiceTests {
[TestMethod]
public void Get_Users_ReturnsUserList() {
//Arrange
var expected = new List<FUser>() {
//populate with some users
};
IMRepository mockRepository = new Mock<IMRepository>();
mockRepository.Setup(_ => _.ExecuteCommandReader()).Returns(expected);

IMService mService = new MService(mockRepository.Object);

//Act
var resultList = mService.GetFUser();

//Assert
Assert.IsTrue(resultList.Count > 0);
}
}


The reason for your initial problem what the the test runner was unable to create the test class as it (the runner) was not build to do DI.



In order to test the subject class, you needed to create an instance of the class and inject any dependencies needed to test the behavior of the method under test.



There really was no need to use the container for such a small isolated test






share|improve this answer

































    1














    You are missing the [TestClass] attribute on the test class (assuming your are using MSTest framework).
    Test classes need to have an empty default constructor or no constructors at all.



    For setting up the tests you can either arrange it the way that you




    1. Manually create the required instances or

    2. Use a mocking framework or

    3. Do the same initializations just like in your application regarding dependency injection, and then resolve the instances as required


    Maybe you also want to take a look, at the Arrange-Act-Assert pattern for unit tests:
    (see http://defragdev.com/blog/?p=783)



    Also keep in mind, that you rather want to test the code and not the DI framework.






    share|improve this answer
























    • Good explanation of the problem and a viable solution.

      – Nkosi
      Nov 15 '18 at 15:24













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53322104%2fioc-in-unittest-class-unity-webapi%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    There seems to be a bit of confusion about how to unit test a class that has dependencies.



    Let us assume the subject under test looks like this



    public class MService: IMService {

    private readonly IMRepository mRepository;

    public MService(IMRepository mRepository) {
    this.mRepository = mRepository;
    }

    public List<FUser> GetFUser() {
    var result = mRepository.ExecuteCommandReader();
    return result
    }
    }


    In order to test the MService.GetFUser you would create an instance of the subject class MService and inject what ever dependencies are needed to test the behavior of the method under test.



    In the following example test, the dependencies will be mocked using Moq mocking framework. You could just as easily create a fake implementation if so desired.



    [TestClass]
    public class MServiceTests {
    [TestMethod]
    public void Get_Users_ReturnsUserList() {
    //Arrange
    var expected = new List<FUser>() {
    //populate with some users
    };
    IMRepository mockRepository = new Mock<IMRepository>();
    mockRepository.Setup(_ => _.ExecuteCommandReader()).Returns(expected);

    IMService mService = new MService(mockRepository.Object);

    //Act
    var resultList = mService.GetFUser();

    //Assert
    Assert.IsTrue(resultList.Count > 0);
    }
    }


    The reason for your initial problem what the the test runner was unable to create the test class as it (the runner) was not build to do DI.



    In order to test the subject class, you needed to create an instance of the class and inject any dependencies needed to test the behavior of the method under test.



    There really was no need to use the container for such a small isolated test






    share|improve this answer






























      2














      There seems to be a bit of confusion about how to unit test a class that has dependencies.



      Let us assume the subject under test looks like this



      public class MService: IMService {

      private readonly IMRepository mRepository;

      public MService(IMRepository mRepository) {
      this.mRepository = mRepository;
      }

      public List<FUser> GetFUser() {
      var result = mRepository.ExecuteCommandReader();
      return result
      }
      }


      In order to test the MService.GetFUser you would create an instance of the subject class MService and inject what ever dependencies are needed to test the behavior of the method under test.



      In the following example test, the dependencies will be mocked using Moq mocking framework. You could just as easily create a fake implementation if so desired.



      [TestClass]
      public class MServiceTests {
      [TestMethod]
      public void Get_Users_ReturnsUserList() {
      //Arrange
      var expected = new List<FUser>() {
      //populate with some users
      };
      IMRepository mockRepository = new Mock<IMRepository>();
      mockRepository.Setup(_ => _.ExecuteCommandReader()).Returns(expected);

      IMService mService = new MService(mockRepository.Object);

      //Act
      var resultList = mService.GetFUser();

      //Assert
      Assert.IsTrue(resultList.Count > 0);
      }
      }


      The reason for your initial problem what the the test runner was unable to create the test class as it (the runner) was not build to do DI.



      In order to test the subject class, you needed to create an instance of the class and inject any dependencies needed to test the behavior of the method under test.



      There really was no need to use the container for such a small isolated test






      share|improve this answer




























        2












        2








        2







        There seems to be a bit of confusion about how to unit test a class that has dependencies.



        Let us assume the subject under test looks like this



        public class MService: IMService {

        private readonly IMRepository mRepository;

        public MService(IMRepository mRepository) {
        this.mRepository = mRepository;
        }

        public List<FUser> GetFUser() {
        var result = mRepository.ExecuteCommandReader();
        return result
        }
        }


        In order to test the MService.GetFUser you would create an instance of the subject class MService and inject what ever dependencies are needed to test the behavior of the method under test.



        In the following example test, the dependencies will be mocked using Moq mocking framework. You could just as easily create a fake implementation if so desired.



        [TestClass]
        public class MServiceTests {
        [TestMethod]
        public void Get_Users_ReturnsUserList() {
        //Arrange
        var expected = new List<FUser>() {
        //populate with some users
        };
        IMRepository mockRepository = new Mock<IMRepository>();
        mockRepository.Setup(_ => _.ExecuteCommandReader()).Returns(expected);

        IMService mService = new MService(mockRepository.Object);

        //Act
        var resultList = mService.GetFUser();

        //Assert
        Assert.IsTrue(resultList.Count > 0);
        }
        }


        The reason for your initial problem what the the test runner was unable to create the test class as it (the runner) was not build to do DI.



        In order to test the subject class, you needed to create an instance of the class and inject any dependencies needed to test the behavior of the method under test.



        There really was no need to use the container for such a small isolated test






        share|improve this answer















        There seems to be a bit of confusion about how to unit test a class that has dependencies.



        Let us assume the subject under test looks like this



        public class MService: IMService {

        private readonly IMRepository mRepository;

        public MService(IMRepository mRepository) {
        this.mRepository = mRepository;
        }

        public List<FUser> GetFUser() {
        var result = mRepository.ExecuteCommandReader();
        return result
        }
        }


        In order to test the MService.GetFUser you would create an instance of the subject class MService and inject what ever dependencies are needed to test the behavior of the method under test.



        In the following example test, the dependencies will be mocked using Moq mocking framework. You could just as easily create a fake implementation if so desired.



        [TestClass]
        public class MServiceTests {
        [TestMethod]
        public void Get_Users_ReturnsUserList() {
        //Arrange
        var expected = new List<FUser>() {
        //populate with some users
        };
        IMRepository mockRepository = new Mock<IMRepository>();
        mockRepository.Setup(_ => _.ExecuteCommandReader()).Returns(expected);

        IMService mService = new MService(mockRepository.Object);

        //Act
        var resultList = mService.GetFUser();

        //Assert
        Assert.IsTrue(resultList.Count > 0);
        }
        }


        The reason for your initial problem what the the test runner was unable to create the test class as it (the runner) was not build to do DI.



        In order to test the subject class, you needed to create an instance of the class and inject any dependencies needed to test the behavior of the method under test.



        There really was no need to use the container for such a small isolated test







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 15:29

























        answered Nov 15 '18 at 15:23









        NkosiNkosi

        118k17135200




        118k17135200

























            1














            You are missing the [TestClass] attribute on the test class (assuming your are using MSTest framework).
            Test classes need to have an empty default constructor or no constructors at all.



            For setting up the tests you can either arrange it the way that you




            1. Manually create the required instances or

            2. Use a mocking framework or

            3. Do the same initializations just like in your application regarding dependency injection, and then resolve the instances as required


            Maybe you also want to take a look, at the Arrange-Act-Assert pattern for unit tests:
            (see http://defragdev.com/blog/?p=783)



            Also keep in mind, that you rather want to test the code and not the DI framework.






            share|improve this answer
























            • Good explanation of the problem and a viable solution.

              – Nkosi
              Nov 15 '18 at 15:24


















            1














            You are missing the [TestClass] attribute on the test class (assuming your are using MSTest framework).
            Test classes need to have an empty default constructor or no constructors at all.



            For setting up the tests you can either arrange it the way that you




            1. Manually create the required instances or

            2. Use a mocking framework or

            3. Do the same initializations just like in your application regarding dependency injection, and then resolve the instances as required


            Maybe you also want to take a look, at the Arrange-Act-Assert pattern for unit tests:
            (see http://defragdev.com/blog/?p=783)



            Also keep in mind, that you rather want to test the code and not the DI framework.






            share|improve this answer
























            • Good explanation of the problem and a viable solution.

              – Nkosi
              Nov 15 '18 at 15:24
















            1












            1








            1







            You are missing the [TestClass] attribute on the test class (assuming your are using MSTest framework).
            Test classes need to have an empty default constructor or no constructors at all.



            For setting up the tests you can either arrange it the way that you




            1. Manually create the required instances or

            2. Use a mocking framework or

            3. Do the same initializations just like in your application regarding dependency injection, and then resolve the instances as required


            Maybe you also want to take a look, at the Arrange-Act-Assert pattern for unit tests:
            (see http://defragdev.com/blog/?p=783)



            Also keep in mind, that you rather want to test the code and not the DI framework.






            share|improve this answer













            You are missing the [TestClass] attribute on the test class (assuming your are using MSTest framework).
            Test classes need to have an empty default constructor or no constructors at all.



            For setting up the tests you can either arrange it the way that you




            1. Manually create the required instances or

            2. Use a mocking framework or

            3. Do the same initializations just like in your application regarding dependency injection, and then resolve the instances as required


            Maybe you also want to take a look, at the Arrange-Act-Assert pattern for unit tests:
            (see http://defragdev.com/blog/?p=783)



            Also keep in mind, that you rather want to test the code and not the DI framework.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 15 '18 at 15:20









            SilvosSilvos

            886




            886













            • Good explanation of the problem and a viable solution.

              – Nkosi
              Nov 15 '18 at 15:24





















            • Good explanation of the problem and a viable solution.

              – Nkosi
              Nov 15 '18 at 15:24



















            Good explanation of the problem and a viable solution.

            – Nkosi
            Nov 15 '18 at 15:24







            Good explanation of the problem and a viable solution.

            – Nkosi
            Nov 15 '18 at 15:24




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53322104%2fioc-in-unittest-class-unity-webapi%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Bressuire

            Vorschmack

            Quarantine