gpt4 book ai didi

c# - 如何用静态方法最小化静态类(UnitOfWork 案例)?

转载 作者:可可西里 更新时间:2023-11-01 08:43:55 25 4
gpt4 key购买 nike

我有这些类(class):

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
}

关于c# - 如何用静态方法最小化静态类(UnitOfWork 案例)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4282415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com