我有这些课:

public static class UnitOfWorkSS
{
  public static IUnitOfWork Begin()
  {
    return IoC.Resolve<IUnitOfWork>();
  }
}

public class PostService
{
  using (IUnitOfWork unitOfWork = UnitOfWorkSS.Begin())
  {
    //don't forget to sanitize html content
    htmlContent = _htmlSanitizer.Sanitize(htmlContent);

    IPost post = _factory.CreatePost(byUser, title, htmlContent);

    _postRepository.Add(post);

    unitOfWork.Commit();
  }
}

如何模拟UnitOfWorkSSunitOfWork类?

最佳答案

似乎您对Begin()的调用所做的唯一一件事就是为该特定接口(interface)返回已配置的类:IUnitOfWork
您只需要确保对Begin()的调用返回IUnitOfWork的模拟实现即可

您可以采用以下两种方法之一:

选项一-重构UnitOfWorkSS,以便您可以设置要返回的IUnitOfWork实例

public static class UnitOfWorkSS
{
    private static IUnitOfWork _unitOfWork;
    public static IUnitOfWork UnitOfWork
    {
        set { _unitOfWork = value; }
        private get{ _unitOfWork ?? (_unitOfWork = IoC.Resolve<IUnitOfWork>()); }
    }

    public static IUnitOfWork Begin()
    {
        return UnitOfWork;
    }
}

[TestMethod]
public void DoStuff()
{
    var mockUnitOfWork = new Mock<IUnitOfWork>();
    UnitOfWorkSS.UnitOfWork = mockUnitOfWork.Object;

    //Do some setup and verify
}

选项二-只需在IoC容器中注册IUnitOfWork的模拟实例
private Mock<IUnitOfWork> _mockUnitOfWork;

[TestInitialize]
public void Init()
{
    _mockUnitOfWork = new Mock<IUnitOfWork>();

    //Making a lot of assumptions about your IoC here...
    IoC.Register<IUnitOfWork>(_mockUnitOfWork.Object);
}

[TestMethod]
public void DoStuff()
{
    _mockUnitOfWork.Setup( ... );

    //Do some verification
}

10-07 16:48