本文介绍了如何起订量静态类的静态方法(的UnitOfWork情况)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些类:

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();
  }
}

我怎么能嘲笑类 UnitOfWorkSS 的UnitOfWork

推荐答案

它看起来像你正在做的与呼叫开始()将返回您配置类特定接口的唯一的事情: IUnitOfWork

It looks like the only thing you are doing with the call to Begin() is returning your configured class for that particular interface: IUnitOfWork

您真的只需要确保您的来电开始()返回一个模拟实现 IUnitOfWork

You really just need to make sure that your call to Begin() returns a mock implementation of IUnitOfWork

一,你能做到这一点有两种方式:

One of two ways you can do this:

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

Option One - Refactor UnitOfWorkSS so that you can set the instance of IUnitOfWork to be returned

public static class UnitOfWorkSS  
{
    private static _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容器

Option Two - Simply register a mock instance of IUnitOfWork with your IoC Container

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
}

这篇关于如何起订量静态类的静态方法(的UnitOfWork情况)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 23:53