This is a migrated thread and some comments may be shown as answers.

How to mock/Ignore datacontext object without constructor.

1 Answer 151 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Kishore
Top achievements
Rank 1
Kishore asked on 06 Mar 2017, 02:50 PM

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.

1 Answer, 1 is accepted

Sort by
0
Kamen Ivanov
Telerik team
answered on 09 Mar 2017, 01:43 PM
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();
Console.WriteLine(instanceToBeReturned.GetHashCode());
 
Mock.Arrange(() => new DataEntities.DataContextContainer()).Returns(instanceToBeReturned);
 
var newInstanceThatIsMocked = new DataEntities.DataContextContainer();
Console.WriteLine(newInstanceThatIsMocked.GetHashCode());
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:
http://www.telerik.com/blogs/mocking-constructors-with-justmock
and 
http://www.telerik.com/forums/mocking-constructor

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

Regards,
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
Tags
General Discussions
Asked by
Kishore
Top achievements
Rank 1
Answers by
Kamen Ivanov
Telerik team
Share this question
or