If given the following code, is it possible to mock the Base class constructor without mocking the derived class constructor so that MyProp gets set?:
public class Base
{
public Base()
{
throw new NotImplementedException();
}
public string MyProp { get; set; }
}
public class Derived : Base
{
public Derived()
{
MyProp = "hello";
}
}
6 Answers, 1 is accepted
You can arrange the base constructor independently:
Mock.Arrange(() =>
new
Base()).DoNothing();
var x =
new
Derived();
Regards,
Stefan
Telerik


I have a further question on this topic. If the base class has an internal constructor, the above doesn't work unless the InternalsVisibleTo attribute is added to the assembly. If the assembly is signed with a strong key, then the test assembly will need to be too. This could quickly become quite an overhead when setting up tests.
Is there an easy alternative to this available?
Due to a short-coming of the non-public mocking API, it is impossible to mock a non-public constructor right now. One of our upcoming releases will feature a relaxed API that allows constructor mocking. In the mean time your only choice is to use InternalsVisibleTo.
Regards,
Stefan
Telerik

The API will be made available in the upcoming service pack.
Regards,
Stefan
Telerik