我是使用rhino mocks进行单元测试的新手,我很困惑如何模拟我在依赖容器中使用统一容器初始化的依赖关系。
根据下面的代码我必须使用两个依赖TestRepository和RedisCacheManager来单元测试“GetHelloWorld”方法。
public class TestController : BaseController
{
private ITestRepository testRepo;
private IRedisCacheManager cacheManager;
public TestController()
{
testRepo = UnityResolver.Resolve<ITestRepository>();
cacheManager = UnityResolver.Resolve<IRedisCacheManager>();
}
public ActionResult GetHelloWorld()
{
LoggerHelper.WriteInfo("Inside GetHelloWorld Method..");
testRepo.PutDataInCustomAzureDB();
cacheManager.Add("Test", "TestData", new TimeSpan(0, 1, 0));
var getData = cacheManager.Get<string>("Test");
cacheManager.Add("Test", "TestData123", new TimeSpan(0, 1, 0));
var getDataa = cacheManager.Get<string>("Test");
LoggerHelper.WriteInfo("Leaving GetHelloWorld Method..");
return null;
}
}
}
答案 0 :(得分:0)
您必须为单元测试项目单独UnityResolver
,并且必须在Resolve
方法中发送模拟对象。对于单元测试项目,它有一个单独的container
,然后是
Mock<IRedisCacheManager> _mockRedis = new Mock<IRedisCacheManager>();
container.RegisterInstance <IRedisCacheManager>(_mockRedis.Object);
另一种方法是在类本身中注入resolver
或依赖项