Нужна помощь в планировании модели класса - PullRequest
0 голосов
/ 03 апреля 2012

Я хочу объявить некоторые функции для тестов. Например:

CountWords(string text)
ExistsWordInText(string text, string searchedWord)
CountOfWord(string text, string searchedWord)

Теперь я хочу объявить «определения испытаний». Эти определения теста будут добавлены в коллекцию и включают в себя функцию и, в зависимости от функции, различные параметры.

Теперь метод будет выполнять все тесты из коллекции testdefintions, и тесты будут возвращать результат.

Я хочу добавить функции в будущем, ничего не меняя.

В данный момент я нахожусь в этой точке:

IFunction-интерфейс

public interface IFunction
{
    #region Methods

    void Run();

    #endregion
}

Любая функция

public class AttributeExistenceFunction : FunctionBase
{
    public override void Run() {
        // Do any test
        throw new FormatException();
    }
}

TestDefinition-Class

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
}

Кто-нибудь знает, как реализовать динамические параметры / результаты?

1 Ответ

1 голос
/ 03 апреля 2012

Я начал с оптимизма, но он оказался очень уродливым.

Я опубликую его в любом случае, так как он все-таки сделает свою работу.

Вы можете легко добавить конструкторы Func для поддержкиДействуйте и потеряйте взлом VoidReturn.

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
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...