[英]MOQ mocking an interface with setter injection
Please the below code snippet 请使用以下代码段
public class FileUploadPresenter
{
private IFileRepository FileRepository
{
get { return UnityManager.Resolve<IFileRepository>(); }
}
public void LoadData(int id)
{
//How can I redirect the below ReadData call to Mocked method in the testcase ?bypassing the FileRepository getter ?
List<FileModel> fileModelList = FileRepository.ReadData(Id);
//Do something with the data
}
}
My unit test case 我的单元测试用例
[TestMethod]
public void TestMethod1()
{
var mock = new Mock<IFileRepository>();
FileModelfm = new FileModel();
fm.FileId = 1;
fm.FileName = "abc";
fm.PolicyTxnId = 10;
List<FileModel> fml = new List<FileModel>();
fml.Add(fm);
mock.Setup(item => item.ReadData(10)).Returns(fml);
FileUploadPresenter FileUploadPresenterobj = new FileUploadPresenter();
obj.LoadData();
}
Here my mocking code is not really working .How can I setup a mock such a way that the interface method call from my invoking class will hit the mocked method ? 在这里,我的模拟代码无法正常工作。如何设置模拟,使调用类中的接口方法调用会击中该模拟方法? Here my interface property is private and readonly . 在这里,我的接口属性是private和readonly。
I think you need to register your mocked instance with UnityManager
. 我认为您需要向UnityManager
注册UnityManager
实例。 The mocked instance is stored in the Object
property of your mock. 模拟的实例存储在模拟的Object
属性中。
[TestMethod]
public void TestMethod1()
{
var mock = new Mock<IFileRepository>();
UnityManager.RegisterInstance<IFileRepository>(mock.Object);
// ..
}
You shouldn't be using the UnityManager in this manner. 您不应该以这种方式使用UnityManager。 Your IFileRepository is a dependency, it should be injected into your FileUploadPresenter. 您的IFileRepository是一个依赖项,应将其注入到FileUploadPresenter中。
What you've implemented here is a service locator pattern, which as a result has made it hard to test. 您在这里实现的是服务定位器模式,因此很难进行测试。
If you change your FileUploadPresenter to have a constructor that takes an IFileRepository. 如果您将FileUploadPresenter更改为具有采用IFileRepository的构造函数。 You can then mock up an IFileRepository for the test. 然后,您可以模拟一个IFileRepository进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.