我开始使用 xUnit.net 和 Moq 进行单元测试。我正在为以下方法编写测试Update()
方法AppService
:
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);
我的问题是,最好的方法是什么?我应该在调用时只使用回调方法Setup()
吗mockAppRespository
?创建虚拟集合并在更新方法上设置期望以修改虚拟集合是否标准?