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

Mock.Create<T>() invoking first constructor instead of default

1 Answer 77 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
DenisCL
Top achievements
Rank 1
DenisCL asked on 20 Sep 2011, 11:29 AM
Hi,

After migrating from 2010 Q1 to 2011 Q2, I am facing an issue with Mock.Create<T>() :

I Have a default constructor which is declared after an overloaded constructor (in which i have checks for invalid values).
When I use Mock.Create<T>(), the first constructor is called (not the default one). Thus, I Get an exception from my checks that I didn't have before. Instead I Want Mock.Create<T>() use my default constructor for mocking my type.

Here is a code that describe the problem (I am using MsTests) :

public class ClassToMock
{
    public int Member { getset; }
    
    public ClassToMock(int member)
    {
        // Performs some checks
        if (member <= 0)
            throw new ArgumentException("Member must be positive");
 
        Member = member;
    }
 
    public ClassToMock()
    {
 
    }
}
 
public class ClassToMock2
{
    public int Member { getset; }
 
    public ClassToMock2()
    {
 
    }
 
    public ClassToMock2(int member)
    {
        // Performs some checks
        if (member <= 0)
            throw new ArgumentException("Member must be positive");
 
        Member = member;
    }
 }

[TestMethod]
public void TestMethod1()
{
    var classToMock = Mock.Create<ClassToMock>(); => Throws ArgumentException
    Assert.IsNotNull(classToMock);
}
 
[TestMethod]
public void TestMethod2()
{
    var classToMock2 = Mock.Create<ClassToMock2>();
    Assert.IsNotNull(classToMock2);
}
Thanks for your help.

Link for sources : http://www.fileserve.com/file/9MFQj6v/JustMockTestProject1.rar


1 Answer, 1 is accepted

Sort by
0
Ricky
Telerik team
answered on 21 Sep 2011, 12:19 PM
Hi Denis,
Thanks for sending the issue. Here you can do two things to get around this:

First, you can use the Constructor.Mocked switch that will skip the base constructor call. In this case, you can write the declaration in the following way:

var classToMock = Mock.Create<ClassToMock>(Contructor.Mocked);


But in case you have some initialization code in the default constructor. You can use the expression overload that will let you specify the target constructor in a strongly typed manner.
var classToMock = Mock.Create<ClassToMock>(() => new ClassToMock());


However by default it should always try to take the default constructor first therefore also adding a task for it in the PITS that can be found here:
http://www.telerik.com/support/pits.aspx#/public/justmock/7926

Kind Regards
Mehfuz
the Telerik team

Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

Tags
General Discussions
Asked by
DenisCL
Top achievements
Rank 1
Answers by
Ricky
Telerik team
Share this question
or