【问题标题】:how can I test method from service when I use unit of work and repository pattern当我使用工作单元和存储库模式时,如何从服务中测试方法
【发布时间】:2013-07-14 16:35:22
【问题描述】:

如何从我的服务中测试 ClassifyComment() 方法。我有那个测试代码:

[TestClass]
public class SpamServiceTest
{
    [TestMethod]
    public void ClassifyCommentTest()
    {
        var spamComments = Builder<Comments>.CreateListOfSize(10).All().With(x => x.Content = "spam spam spam")
            .Build().AsQueryable();

        var mocker = new AutoMoqer();

        mocker.GetMock<IUnitOfWork>()
                .Setup(x => x.CommentsRepository.GetComments(It.Is<bool>(y => y == true)))
                .Returns(spamComments);

        //.......
    }
}

但它给了我错误:无法实例化类的代理:CommentsRepository。找不到无参数构造函数。

下面是我要测试的代码:

public class SpamService : ISpamService
{
    private readonly IUnitOfWork _unitOfWork;

    public SpamService(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }

    public bool ClassifyComment(Comments comment)
    {
        var spam = _unitOfWork.CommentsRepository.GetComments(true).ToList();
        //.............
    }
}

public class UnitOfWork : IUnitOfWork
{
    private DatabaseContext context = new DatabaseContext();
    private CommentsRepository commentsRepository;

    public CommentsRepository CommentsRepository
    {
        get
        {
            if (this.commentsRepository == null)
            {
                this.commentsRepository = new CommentsRepository(context);
            }
            return commentsRepository;
        }
    }          
}

public class CommentsRepository : ICommentsRepository
{
    private DatabaseContext context;

    public CommentsRepository(DatabaseContext context)
    {
        this.context = context;
    }

    public virtual IQueryable<Comments> GetComments(bool isSpam)
    {
        //.......
    }
}

【问题讨论】:

    标签: c# asp.net asp.net-mvc unit-testing moq


    【解决方案1】:

    IUnityOfWork 应该返回一个ICommentsRepository,即一个接口,而不是一个实现。 IUnityOfWork 的模拟应该返回 ICommentsRepository 的模拟。

    让抽象与其他抽象一起工作,而不是与实现一起工作。

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多