Specflow - сбой TearDown для тестового устройства - System.ArgumentNullException: значение не может быть нулевым. (Параметр «ключ») - PullRequest
0 голосов
/ 06 ноября 2019

Я работаю с автоматизацией тестирования, используя Specflow и Selenium , но к тому времени, когда я пытаюсь выполнить свой тест, я сталкиваюсь с этими сообщениями об ошибках:

  • Мой вопрос не в том, что такое исключение NullReferenceException, а в том, что (и где) этот параметр 'key' указал в качестве причины исключения.

TearDownне удалось выполнить тестовое устройство MyProject.Features.MyFeature System.ArgumentNullException: значение не может быть нулевым. (Параметр «ключ») TearDown: System.NullReferenceException: ссылка на объект не установлена ​​для экземпляра объекта.

И:

Сообщение об ошибке: OneTimeSetUp: System. ArgumentNullException: значение не может быть нулевым. (Параметр «ключ»)

Это мой сценарий:

Scenario: Accessing the screen for the first time
    Given I accessed the screen for the first time
    Then the result grid should only show the phrase "Lorem ipsum"

Это мой файл StepDefinition.cs:

    [Binding]
    public class StepDefinition
    {
        PageObject pageObject = new PageObject();

        [Given(@"I accessed the screen for the first time")]
        public void GivenIAccessedTheScreenForTheFirstTime()
        {
            pageObject.NavigateToScreen();
        }

        [Then(@"the result grid should only show the phrase (.*)")]
        public void ThenTheResultGridShouldOnlyShowThePhrase(string phrase)
        {
            Assert.True(pageObject.isPhraseDisplayed(phrase));
        }        
    }

Это мой PageObjectФайл .cs:

        public PageObject() : base(){ } //I use a BasePageObject.cs file also

        public void NavigateToScreen()
        {
            driver.Navigate().GoToUrl(_urlHere_);
        }
        public bool isPhraseDisplayed(string phrase)
        {
            wait.Until(u => u.FindElement(_byIdOfWebElementHere_).Displayed);

            IWebElement element = driver.FindElement(_byIdOfWebElementHere_);
            return element.Displayed;
        }

И это файл BasePageObject.cs, который реализует интерфейс IDisposable:

        protected IWebDriver driver { get; set; }
        protected WebDriverWait wait { get; set; }

        public BasePageObject()
        {
            driver = new ChromeDriver();
        }

        [AfterScenario]
        public void Dispose()
        {
            driver.Close();
            driver.Quit();
            driver.Dispose();
        }
    }

Трассировка стека исключений:

Starting test execution, please wait...

A total of 1 test files matched the specified pattern.
TearDown failed for test fixture MyProject.Features.MyFeature
System.ArgumentNullException : Value cannot be null. (Parameter 'key')
TearDown : System.NullReferenceException : Object reference not set to an instance of an object.
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.FindAttributeConstructorArg(ParameterInfo parameterInfo, Dictionary`2 namedAttributeValues)
   at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.<>c__DisplayClass8_0.<CreateAttribute>b__7(ParameterInfo p)
   at System.Linq.Enumerable.SelectArrayIterator`2.ToArray()
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.CreateAttribute(Attribute attribute)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.ToArray()
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.GetAttributes(IEnumerable`1 customAttributes)
   at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.CreateBindingSourceMethod(MethodInfo methodDefinition)
   at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.BuildBindingsFromType(Type type)
   at TechTalk.SpecFlow.Bindings.Discovery.RuntimeBindingRegistryBuilder.BuildBindingsFromAssembly(Assembly assembly)
   at TechTalk.SpecFlow.TestRunnerManager.BuildBindingRegistry(IEnumerable`1 bindingAssemblies)
   at TechTalk.SpecFlow.TestRunnerManager.InitializeBindingRegistry(ITestRunner testRunner)
   at TechTalk.SpecFlow.TestRunnerManager.CreateTestRunner(Int32 threadId)
   at TechTalk.SpecFlow.TestRunnerManager.GetTestRunnerWithoutExceptionHandling(Int32 threadId)
   at TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(Int32 threadId)
   at TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(Assembly testAssembly, Nullable`1 managedThreadId)
   at MyProject.Features.MyFeature.FeatureSetup()
--TearDown
   at MyProject.Features.MyFeature.FeatureTearDown()
  X AcessandoATelaDeConsultaPelaPrimeiraVez [< 1ms]
  Error Message:
   OneTimeSetUp: System.ArgumentNullException : Value cannot be null. (Parameter 'key')

Results File: C:\Users\FAMG\AppData\Local\Temp\test-explorer-GvcYR7\0.trx

Total tests: 1
     Failed: 1
 Total time: 3,7733 Seconds

На мой взгляд, важно отметить:

  • Я использую VSCode , а не Visual Studio.
  • В моем проекте установлен тестовый прогон NUnit.

1 Ответ

0 голосов
/ 07 ноября 2019

Я только что побежал к этой точной вещи.
Источник ошибки исходит из размышления о типе: System.Runtime.CompilerServices.NullableContextAttribute.

Похоже, какой-то ожидаемый конструктор MethodInfo Имя равно NULL.

Короче говоря: .NET Core 2.1, 2.2 работа. SpecFlow (3.0.225), похоже, не работает с .Net Core 3.0.

Хорошие новости: включите предварительный выпуск для Nuget и обновите бета-версию SpecFlow и связанных пакетов (Nunit и друзья) до(3.1.52-бета) последние работы.

Основной выпуск SpecFlow 3.1, вероятно, будет поддерживать .Net Core 3.0.

...