1

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

1 回答 1

4

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

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

于 2013-07-14T16:57:00.830 回答