【发布时间】:2012-03-01 12:50:05
【问题描述】:
我开始使用 xUnit.net 和 Moq 进行单元测试。我正在为AppService 中的Update() 方法编写测试方法:
public class AppService : IAppService
{
public virtual void Update(App entity)
{
if (entity == null)
{
throw new ArgumentNullException("App");
}
_appRepository.Update(entity);
_cacheManager.Remove(Key);
}
}
_appRepository 和 _cacheManager 分别派生自接口 IRepository<App> 和 ICacheManager。我正在使用 moq 在我的单元测试中创建这些对象的模拟,如下所示:
[Fact]
public void UpdateTest()
{
mockAppRepository = new Mock<IRepository<App>>();
mockCacheManager = new Mock<ICacheManager>();
// how to setup mock?
// mockAppRepository.Setup();
AppService target = new AppService(mockAppRepository.Object,
mockCacheManager.Object);
App entity = new App();
target.Update(entity);
Assert.NotNull(entity);
}
我知道我需要模拟来模拟存储库中的更新成功,特别是对 _appRepository.Update(entity); 的调用
我的问题是,最好的方法是什么?当我在mockAppRespository 上调用Setup() 时,我应该只使用回调方法吗?创建一个虚拟集合并在更新方法上设置期望来修改虚拟集合是否标准?
【问题讨论】:
标签: unit-testing repository moq xunit.net