[英]Fake a static method of a non-static class
I have a non-static class with a static method that I want to shim it.我有一个非静态 class 和 static 方法,我想对其进行填充。
public class MyClass
{
static MyClass()
{
//do constructor things
}
public static void MyMethod(string str)
{
//do something
}
}
This static method is called from some part of the code I want to test ( MyClass.MyMethod("some string") ), but I'm not interested on MyMethod behavior.这个 static 方法是从我要测试的代码的某些部分( MyClass.MyMethod("some string") )调用的,但我对 MyMethod 的行为不感兴趣。 I need to shim it.
我需要垫它。 My try is:
我的尝试是:
MyClassNamespace.Fakes.ShimMyClass.MyMethod = ("some string") => {};
But MyMethod is missing, I believe because the class is not static.但是缺少 MyMethod,我相信是因为 class 不是 static。
How can I shim it like it was a static class?我怎样才能像 static class 一样填充它? I have read that it's possible to shim the Contructor and simulate some methods, and maybe that is a better choice, but I don't know how to do it.
我已经读过可以填充构造器并模拟一些方法,也许这是一个更好的选择,但我不知道该怎么做。
You need to define the Shim on AllInstances
您需要在
AllInstances
上定义 Shim
MyClassNamespace.Fakes.ShimMyClass.AllInstances.MyMethodString = ("some string") => {};
If you notice in above code the name of method in generated shim is with parameter type (that's the way Shims are generated).如果您在上面的代码中注意到生成的垫片中的方法名称是带有参数类型的(这就是垫片的生成方式)。
I'm not sure for 100% what you mean, but it looks like you want to store an static action.我不确定 100% 你的意思,但看起来你想存储一个 static 动作。
In my example you assign a lambda expression to the static field.在我的示例中,您将 lambda 表达式分配给 static 字段。 The instances can call this Action:
实例可以调用此操作:
public class MyClass
{
public static Action<string> LogMehod;
public void Log(string s)
{
// call the static log method if it is assigned.
if(LogMehod != null)
LogMehod(User + ": " + s);
}
public string User {get;set;}
}
class Program
{
static Main()
{
// assign an lambda expression, which displays the passed string.
MyClass.LogMehod = s =>
{
Console.WriteLine(s);
}
// create an instance of MyClass
var user1 = new MyClass();
user1.User = "User1";
user1.Log("bla");
var user2 = new MyClass();
user2.User = "User2";
user2.Log("also bla");
Console.ReadLine();
}
}
Gives:给出:
User1: bla
User2: also bla
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.