Following code will generate run-time error (Parent does
not have default constructor).
using System;
using DotNetMock.Dynamic;
namespace delitDMWithoutDefConstructor {
public class Base {
public Base(string msg) {}
public Base() {}
}
public class Derived : Base {
public Derived(string msg) : base(msg) {}
// Uncomment to resolve the error.
// public Derived() {}
}
public class Class1 {
[STAThread]
static void Main(string[] args) {
new DynamicMockEx(typeof(Derived));
}
}
}
Solutions?
1. Add constructor with signature matching to one of the
patern class (mocked class), and call it with some
default values.
2. Instead of generating new class that derives from the
given class, copy the class and replace method code.
Logged In: YES
user_id=1170022
The problem can be solved by simply defining a default
constructor on a mock object, therefore eliminating a need
for default constructor in the class to be mocked. Here is a
test fixture:
/// <summary>
/// Test mocking of class with no public default constructor.
/// </summary>
/// <author>Roman V. Gavrilov</author>
[TestFixture]
public class NoDefConstructorMockTests {
/// <summary>
/// Test class.
/// </summary>
public class NoDefConstructorClass {
public NoDefConstructorClass(object obj) {}
}
[Test]
public void NoDefConstructorClassMock() {
DynamicMockEx mock = new DynamicMockEx(typeof
(NoDefConstructorClass));
object result = mock.Object;
Assert.IsNotNull(result, "Mock object did not get
generated.");
}
}
I just added call to following method (of class
MockClassBuilder) from ClassGenerator.Generate
/// <summary>
/// Implement class's default constructor.
/// </summary>
public void ImplementDefaultConstructor() {
ConstructorBuilder cb =
_typeBuilder.DefineConstructor(MethodAttributes.Public,
CallingConventions.Standard, Type.EmptyTypes);
ILGenerator il = cb.GetILGenerator();
il.Emit(OpCodes.Ret);
}
Comments:
Default constructor does not initializes any mock object's
members - but there is none anyway.