我想为测试声明一些函数。例如:
CountWords(string text)
ExistsWordInText(string text, string searchedWord)
CountOfWord(string text, string searchedWord)
现在我要声明“testdefintions”。这些测试定义将添加到集合中,并包含一个函数,并根据函数,包含不同的参数。
现在,方法将执行testdefintions集合中的所有测试,测试将返回结果。
我希望将来添加功能而不更改任何其他内容。
此刻我正处于这一点:
■功能接口
public interface IFunction
{
#region Methods
void Run();
#endregion
}
任何功能
public class AttributeExistenceFunction : FunctionBase
{
public override void Run() {
// Do any test
throw new FormatException();
}
}
TestDefinition级
public class TestDefinition : ITestDefinition
{
#region Fields
public IFunction Function { get; set; }
#endregion
#region Constructor
public TestDefinition(IFunction function)
{
this.Function = function;
}
#endregion
#region Methods
public void Run(Uri site)
{
this.Function.Run();
}
#endregion
}
有人知道如何实现动态参数/结果吗?
答案 0 :(得分:1)
我开始乐观,但结果真的太丑了。
我会发布它,因为它毕竟完成了这项任务。
您可以轻松添加Func构造函数以支持Action并丢失VoidReturn hack。
public class Func
{
public readonly MethodInfo Method;
public readonly object Target;
#region Ctors
public static Func Get<TResult>(Func<TResult> func)
{
return new Func(func.Method, func.Target);
}
public static Func Get<T, TResult>(Func<T, TResult> func)
{
return new Func(func.Method, func.Target);
}
public static Func Get<T1, T2, TResult>(Func<T1, T2, TResult> func)
{
return new Func(func.Method, func.Target);
}
public static Func Get<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> func)
{
return new Func(func.Method, func.Target);
}
#endregion
private Func(MethodInfo method, object target)
{
this.Method = method;
this.Target = target;
}
public object Run(params object[] parameters)
{
return this.Method.Invoke(this.Target, parameters);
}
}
public class MyClass
{
public string Data { get; set; }
public int Add(int x, int y)
{
return x + y;
}
public bool IsZero(int i)
{
return i == 0;
}
public void Print(object msg)
{
Console.WriteLine(msg);
}
public bool ValidateData()
{
return string.IsNullOrEmpty(this.Data);
}
public void TestMethods()
{
var tests = new Dictionary<Func, object[][]>
{
{
Func.Get<int, int, int>(this.Add),
new[]
{
new object[] {2, 3},
new object[] {5, 0},
new object[] {10, -2}
}
},
{
Func.Get<int, bool>(this.IsZero),
new[]
{
new object[] {1},
new object[] {0},
new object[] {-1}
}
},
{
Func.Get<object, VoidReturn>(o =>
{
this.Print(o);
return VoidReturn.Blank;
}),
new[]
{
new object[] {"Msg1"},
new object[] {"Msg2"},
new object[] {"Msg3"}
}
},
{Func.Get(this.ValidateData), null}
};
foreach (var testFunc in tests)
{
Console.WriteLine("Testing method: " + testFunc.Key.Method.Name);
Console.WriteLine();
foreach (var parameters in testFunc.Value)
{
Console.WriteLine("Parameters: " + string.Join(", ", parameters));
var result = testFunc.Key.Run(parameters);
Console.WriteLine(result is VoidReturn ? "*void" : ("Returned: " + result));
Console.WriteLine();
}
Console.WriteLine("________________________________");
Console.WriteLine();
}
}
private enum VoidReturn
{
Blank
}
}