My method has a type parameter, so I am trying in my unit test to define a mock object and pass a type of it with a hope, that the instance of this type will mock the method as I have defined it. But if I call a method of my mock after I have created it with Activator.CreateInstance(), I become NotImplementedException.
Is it possible to mock a method with using of Activator.CreateInstance()?
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
public class MyTestClass
{
[TestMethod]
public void TestDoFunc()
{
var vmod = new MyViewModel();
var mock = new Mock<IAmAnInterface<MyViewModel>>();
mock.Setup(x => x.DoInterfaceFunc(vmod)).Callback<MyViewModel>((viewModel) => { viewModel.Created = true; }).Returns(true);
Assert.IsTrue(mock.Object.DoInterfaceFunc<MyViewModel>(vmod));//this works
Assert.IsTrue(vmod.Created);//this works
var mockObjFromActivator = Activator.CreateInstance(mock.Object.GetType()) as IAmAnInterface<MyViewModel>;
Assert.IsTrue(mockObjFromActivator.DoInterfaceFunc<MyViewModel>(vmod));//this throw NotImplementedException
}
}
public class MyViewModel { public bool Created { get; set; } }
public interface IAmAnInterface<TViewModel> { bool DoInterfaceFunc<TViewModel>(TViewModel vmod); }
Aucun commentaire:
Enregistrer un commentaire