How to mock/Ignore datacontext object without constructor.

2 posts, 0 answers
  1. Kishore
    Kishore avatar
    2 posts
    Member since:
    Feb 2017

    Posted 06 Mar 2017 Link to this post

    I have to implement a unit test method that needs to mock datacontextcontainer. Below is the code i have to mock

    using (var dcc = new DataEntities.DataContextContainer())            



    How can i mock DataEntities.DataContextContainer(). When ever i use to call this statement i m getting new instance. Can some please help me on this.

  2. Kamen Ivanov
    Kamen Ivanov avatar
    80 posts

    Posted 09 Mar 2017 Link to this post

    Hello Kishore,

    Thank you for your interest in JustMock.
    Mocking a constructor should be done the same way as any other member or method of a class.

    Here is example code where we create one instance and then mock the constructor to always return that value:
    var instanceToBeReturned = new DataEntities.DataContextContainer();
    Mock.Arrange(() => new DataEntities.DataContextContainer()).Returns(instanceToBeReturned);
    var newInstanceThatIsMocked = new DataEntities.DataContextContainer();
    If you execute the code you will see that the hash code of both instances is the same.

    You might also want to take a look at these examples too:

    Let us know if that helps you in for your scenario.

    Kamen Ivanov
    Telerik by Progress
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Back to Top