예제 #1
0
        protected override object CallTestMethod(object testClassInstance)
        {
            try
            {
                return(TestMethod.Invoke(testClassInstance, TestMethodArguments));
            }
            catch (Exception e)
            {
                if (Settings.TakeScreenshotOnFailure)
                {
                    try
                    {
                        TakeScreenShot(Test.DisplayName);
                    }
                    catch (Exception exception)
                    {
                        Aggregator.Add(exception);
                    }
                }

                if (e is TargetInvocationException && e.InnerException is FakeException)
                {
                    return(null);
                }

                throw;
            }
        }
        public void Update()
        {
            if (!isTriggered && uGUI.isInitialized)
            {
                testMethod?.Invoke();

                isTriggered = true;
            }
        }
        protected override object CallTestMethod(object testClassInstance)
        {
            var asyncSyncContext = (AsyncTestSyncContext)SynchronizationContext.Current;

            //
            // Run the test method inside of our iterator.  Note that BenchmarkIterator.Run ensures that only one test
            // method is running at any given time, so we don't need extra synchronization here.
            //
            var benchmarkAttr = (BenchmarkAttribute)TestMethod.GetCustomAttribute(typeof(BenchmarkAttribute));
            var iterator      = new BenchmarkIteratorImpl(DisplayName, benchmarkAttr.InnerIterationCount);

            return(iterator.RunAsync(async() =>
            {
                var success = false;
                BenchmarkEventSource.Log.BenchmarkStart(BenchmarkConfiguration.Instance.RunId, DisplayName);
                try
                {
                    var result = TestMethod.Invoke(testClassInstance, TestMethodArguments);

                    var task = result as Task;
                    if (task != null)
                    {
                        await task;
                        success = true;
                    }
                    else
                    {
                        var ex = await asyncSyncContext.WaitForCompletionAsync();
                        if (ex == null)
                        {
                            success = true;
                        }
                        else
                        {
                            Aggregator.Add(ex);
                        }
                    }

                    if (iterator.IterationStopReason == "NoIterations")
                    {
                        success = false;
                        throw new Exception("Benchmark did not execute any iterations.  Please use one of the iteration methods in Microsoft.Xunit.Performance.Benchmark");
                    }
                }
                finally
                {
                    var stopReason = success ? iterator.IterationStopReason : "TestFailed";
                    BenchmarkEventSource.Log.BenchmarkStop(BenchmarkConfiguration.Instance.RunId, DisplayName, stopReason);
                    BenchmarkEventSource.Log.Flush();
                }
            }));
        }
예제 #4
0
        protected override object CallTestMethod(object testClassInstance)
        {
            var modules             = new Dictionary <string, ModuleDefinition>();
            var testType            = ResolveType(TestMethod.DeclaringType, modules);
            var testMethod          = testType.Methods.Single(m => m.MetadataToken.ToInt32() == TestMethod.MetadataToken);
            var methodTypeArguments = TestMethod.GetGenericArguments().Select(t => ResolveType(t, modules)).ToArray();

            var actualResult      = TestMethod.Invoke(testClassInstance, TestMethodArguments);
            var interpretedResult = new Interpreter().InterpretCall(
                new TypeReference[0], testMethod, methodTypeArguments, testClassInstance, TestMethodArguments
                );

            Assert.Equal(actualResult, interpretedResult);
            return(null);
        }
예제 #5
0
        public object Invoke(System.IO.TextWriter writer)
        {
            var    p   = _methodInfo.GetParameters();
            object res = null;

            if (p.Length == 0)
            {
                res = TestMethod.Invoke(MethodOwnerType.Instance, null);
            }
            else if (p.Length == 1 && p[0].ParameterType.FullName == "System.IO.TextWriter")
            {
                object[] parametersArray = new object[] { writer };
                res = TestMethod.Invoke(MethodOwnerType.Instance, parametersArray);
            }


            return(res);
        }
        public static Dictionary <MethodInfo, bool> Run(Assembly assembly)
        {
            Dictionary <MethodInfo, bool> methodMarkPairs = new Dictionary <MethodInfo, bool>();
            bool markOfTestMethod;

            foreach (var TestMethod in SearchTestMethodsInAssembly(assembly))
            {
                markOfTestMethod = true;
                var ObjectOfTestClass = Activator.CreateInstance(TestMethod.DeclaringType);
                try
                {
                    TestMethod.Invoke(ObjectOfTestClass, new object[] { });
                }
                catch (TargetInvocationException)
                {
                    markOfTestMethod = false;
                }
                methodMarkPairs.Add(TestMethod, markOfTestMethod);
            }
            return(methodMarkPairs);
        }
예제 #7
0
        static void Main(string[] args)
        {
            var assembly = Assembly.LoadFrom("LibraryTest.dll");

            //который запускается перед остальными тестами
            MethodInfo StartMethod = null;

            //метод через который запускаются методы с атрибутом Test
            MethodInfo TestMethod;

            // Ищем классы
            foreach (Type TestType in assembly.GetTypes())
            {
                // Ищем классы, которые имеют атрибут TestFixture
                if (TestType.IsDefined(typeof(NUnit.Framework.TestFixtureAttribute), false))
                {
                    //создаем экземпляр такого класса
                    object obj = Activator.CreateInstance(TestType);

                    // Ищем метод, который имеет атрибут SetUp, когда находим
                    // приcваиваем StartMethod это значение
                    // И дальше начинается цикл на запуск методов с атрибутом Test
                    foreach (MethodInfo mi in TestType.GetMethods())
                    {
                        if (mi.IsDefined(typeof(NUnit.Framework.SetUpAttribute), false))
                        {
                            StartMethod = TestType.GetMethod(mi.Name.ToString());
                            break;
                        }
                    }
                    // Ищем методы этого класса

                    foreach (MethodInfo mi in TestType.GetMethods())
                    {
                        // Ищем методы, которые имеют атрибут Test
                        if (mi.IsDefined(typeof(NUnit.Framework.TestAttribute), false))
                        {
                            //Пишем имя метода
                            Console.WriteLine(mi.Name);

                            TestMethod = TestType.GetMethod(mi.Name.ToString());

                            //запускаем SetUp метод
                            try
                            {
                                if (StartMethod != null)
                                {
                                    StartMethod.Invoke(obj, new object[] { });
                                }
                            }
                            catch (Exception e)
                            {
                            }
                            // пытаемся запустить тестовый метод, если выдает ошибку выводим ее
                            try
                            {
                                TestMethod.Invoke(obj, new object[] { });
                                Console.WriteLine("тест прошел успешно");
                                Console.WriteLine();
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("тест прошел с ошибкой");
                                Console.WriteLine(e.InnerException.Message);
                            }
                        }
                    }
                }
                break;
            }
        }
예제 #8
0
        /// <inheritdoc/>
        protected override async Task <decimal> InvokeTestMethodAsync(object testClassInstance)
        {
            var oldSyncContext = SynchronizationContext.Current;

            try
            {
                var asyncSyncContext = new AsyncTestSyncContext(oldSyncContext);
                SetSynchronizationContext(asyncSyncContext);

                Exception testException = null;

                await Aggregator.RunAsync(
                    () => Timer.AggregateAsync(
                        async() =>
                {
                    var parameterCount = TestMethod.GetParameters().Length;
                    var valueCount     = TestMethodArguments == null ? 0 : TestMethodArguments.Length;
                    if (parameterCount != valueCount)
                    {
                        Aggregator.Add(
                            new InvalidOperationException(
                                $"The test method expected {parameterCount} parameter value{(parameterCount == 1 ? "" : "s")}," +
                                $"but {valueCount} parameter value{(valueCount == 1 ? "" : "s")} {(valueCount == 1 ? "was" : "were")} provided.")
                            );
                    }
                    else
                    {
                        try {
                            var result = TestMethod.Invoke(testClassInstance, TestMethodArguments);
                            var task   = result as Task;
                            if (task != null)
                            {
                                await task;
                            }
                            else
                            {
                                var ex = await asyncSyncContext.WaitForCompletionAsync();
                                if (ex != null)
                                {
                                    testException = ex;
                                    Aggregator.Add(ex);
                                }
                            }
                        } catch (Exception ex) {
                            testException = ex;
                            throw;
                        }
                    }
                }
                        )
                    );

                if (testException != null)
                {
                    var handleTestFailure = testClassInstance as INeedToKnowTestFailure;
                    if (handleTestFailure != null)
                    {
                        await
                        Aggregator.RunAsync(
                            () => handleTestFailure.HandleFailureAsync(Test, testException));
                    }
                }
            }
            finally
            {
                SetSynchronizationContext(oldSyncContext);
            }

            return(Timer.Total);
        }