簡體   English   中英

當我使用工作單元和存儲庫模式時,如何從服務測試方法

[英]how can I test method from service when I use unit of work and repository pattern

如何從我的服務測試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)
    {
        //.......
    }
}

IUnityOfWork應該返回一個ICommentsRepository ,即一個接口,而不是一個實現。 IUnityOfWork的模擬應返回ICommentsRepository的模擬。

讓抽象適用於其他抽象,而不是實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM