3

我开始使用 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?创建虚拟集合并在更新方法上设置期望以修改虚拟集合是否标准?

4

1 回答 1

4

通常像这样简单的测试就可以了。

mockAppRepository.Verify(d=> d.Update(It.IsAny<App>()), Times.Once());

使用 Moq,如果返回结果很重要,您只需要 .Setup() 进行这样的测试。

编辑:
为了说明抛出异常,根据注释,您将在运行代码之前进行以下设置。

mockAppRepository.Setup(d=> d.Update(It.IsAny<App>())).Throws<Exception>();
于 2012-02-09T03:38:14.400 回答