当我使用工作单元和存储库模式时,如何从服务测试方法

时间:2013-07-14 16:35:23

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

如何从我的服务中测试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)
    {
        //.......
    }
}

1 个答案:

答案 0 :(得分:4)

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

让抽象适用于其他抽象,而不是实现。