Product Bundles
DevCraft
All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with:
Web
Mobile
Document Management
Desktop
Reporting
Testing & Mocking
CMS
UI/UX Tools
Debugging
Free Tools
Hi,
Please let me know on how do we mock a private constructor.
Example:
Hello Chandra,
I have slightly touched the test target in the following way:
public class TestTarget { public int Number { get; private set; } private TestTarget(int number) { this.Number = number; } }
The desired mocking could be done like this:
[TestMethod] public void TestMethod1() { var mock = Mock.Create<TestTarget>(); Mock.Arrange(() => mock.Number).IgnoreInstance().Returns(100); var constructorInfo = typeof(TestTarget).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(int) }, null); Mock.NonPublic.Arrange<TestTarget>(constructorInfo, Arg.Expr.AnyInt).Returns(mock); var actual = constructorInfo.Invoke(new object[] { 5 }) as TestTarget; Assert.AreEqual(mock.Number, actual.Number); }
I hope that provided information answers your question. If you need further assistance do not hesitate to write us back.
Regards, Ivo Progress Telerik
Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.
Thanks Ivo for the information. on the similar lines, I have a query Regarding Abstract class constructors.
public abstract class TestTarget:Exception { public TestTarget(string message,Exception inner):base(message,inner) { } }
How do we handle this case?
Please let me know.
Regards,
Chandra.
Find the sample test target
public abstract class AbstractExceptionBase : Exception { protected AbstractExceptionBase(string message, Exception inner) // by convension, it is recommended to be protected : base(message, inner) { } } public class DerivedException : AbstractExceptionBase { public DerivedException(string message, Exception inner) : base(message, inner) { } }
and the unit test
[TestMethod] public void TestMethod2() { var mockAbstractExceptionBase = Mock.Create<AbstractExceptionBase>(); string expectedMessage = null; Exception expectedInner = null; var constructorInfo = typeof(AbstractExceptionBase).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(string), typeof(Exception) }, null); Mock.NonPublic.Arrange<AbstractExceptionBase>(constructorInfo, Arg.Expr.AnyString, Arg.Expr.IsAny<Exception>()) .Returns( (string message, Exception inner) => { expectedMessage = message; expectedInner = inner; return mockAbstractExceptionBase; }) .MustBeCalled(); string actualMessage = "Exception message"; Exception actualInner = new NotSupportedException(); var acual = new DerivedException(actualMessage, actualInner); Mock.Assert(constructorInfo); Assert.AreEqual(expectedMessage, actualMessage); Assert.AreEqual(expectedInner, actualInner); }