【问题标题】:How to write a unit test for a repository update method?如何为存储库更新方法编写单元测试?
【发布时间】: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


    【解决方案1】:

    通常是这样简单的测试。

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

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

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

    mockAppRepository.Setup(d=> d.Update(It.IsAny<App>())).Throws<Exception>();
    

    【讨论】:

    • 谢谢,这是我最初的想法,但似乎应该还有更多。
    • 通常您还会设置一个测试,其中存储库更新会引发异常?
    • @mhornfeck:我也会设置一个例外。
    猜你喜欢
    • 2013-01-18
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-31
    • 2019-06-12
    • 2020-06-30
    • 1970-01-01
    相关资源
    最近更新 更多