gpt4 book ai didi

c# - 使用 Microsoft fakes 伪造静态/单例类/方法

转载 作者:行者123 更新时间:2023-11-30 12:41:42 28 4
gpt4 key购买 nike

我有一个具有私有(private)构造函数并通过公共(public)静态方法(单例类)访问的类。无法在假货中创建此类的单例对象。

public class MyBusinessManager : BusinessManager
{
private MyBusinessManager objMyBusinessManager;

private MyBusinessManager (MyBusinessManager dvqsDataManager)
{
objMyBusinessManager= dvqsDataManager;
}
public static MyBusinessManager GetInstance() // out
{
MyBusinessManager dvqsDataMgr = new MyBusinessManager();

return new MyBusinessManager (dvqsDataMgr);
}

public bool MyBusinessManagerMethod (int bm)
{
if(bm == 0)
return true;

return false;
}
}

我想测试以下方法:

public class MyService
{
public bool MyServiceMethod(int serviceParam)
{
MyBusinessManager dvqBusinessManager = MyBusinessManager.GetInstance(); // make fake call
return dvqBusinessManager.MyBusinessManagerMethod(serviceParam); // make fake service call
}
}

我的测试类:

[TestClass]
public class MyService_UT
{
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
ShimMyBusinessManager.GetInstance = () => { return new ShimMyBusinessManager(); };
ShimMyBusinessManager.AllInstances.MyServiceMethodInt32 = (a) =>{
return true;
}
MyService obj = new MyService();
Assert.IsTrue(obj.MyServiceMethod(1))// doesn't call fake method
}
}
}

在这种情况下如何调用假方法?无法使用此代码创建假的实例。

最佳答案

我建议将 dvqBusinessManager 的创建移到方法之外。

这边

    MyBusinessManager dvqBusinessManager = MyBusinessManager.GetInstance();
public bool MyServiceMethod(int serviceParam)
{
return dvqBusinessManager.MyBusinessManagerMethod(serviceParam); // make fake service call
}

或者

    public bool MyServiceMethod(int serviceParam)
{
MyBusinessManager dvqBusinessManager = MyBusinessManager.GetInstance();
MyServiceTestableMethod(dvqBusinessManager, serviceParam);
}

public bool MyServiceTestableMethod(MyBusinessManager manager, int serviceParam)
{
return manager.MyBusinessManagerMethod(serviceParam);
}

因此您可以向该方法中注入(inject)一个假对象并对其进行测试,而无需调用 GetInstance 方法。

或者您可以实现和使用工厂模式并在那里隐藏静态调用。

    public interface IServiceFactory 
{
MyBusinessManager GetInstance();
}

public class ServiceFactory : IServiceFactory
{
public MyBusinessManager GetInstance()
{
return MyBusinessManager.GetInstance();
}
}

IServiceFactory factory = new ServiceFactory();
public bool MyServiceMethod(int serviceParam)
{
MyBusinessManager dvqBusinessManager = factory.GetInstance();
dvqBusinessManager.MyBusinessManagerMethod(serviceParam);
}

但是如果您仍然想在不更改代码的情况下模拟静态调用,则应该像本例中那样使用 Shims http://www.richonsoftware.com/post/2012/04/05/using-stubs-and-shim-to-test-with-microsoft-fakes-in-visual-studio-11.aspx .

关于c# - 使用 Microsoft fakes 伪造静态/单例类/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36740164/

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