I am creating a new framework as PageFactory has been deprecated.
I am getting the error
BoDi.ObjectContainerException : Interface cannot be resolved: OpenQA.Selenium.IWebDriver (resolution path: UnitTestProject1.Base)
TearDown : BoDi.ObjectContainerException : Interface cannot be resolved: OpenQA.Selenium.IWebDriver (resolution path: UnitTestProject1.Base)
My code snippet of my framework is below. I am not sure how I can resolve this. I am aware I could use Context Injection but am not sure what attributes from my framework I should move and to where.
I was thinking should I move the IWedriver Driver to a class and call this in a constructor but not sure where I should call it in the steps file.
Some help to resolve this issue appreciated, thanks.
using System;
using System.Collections.Generic;
using System.Text;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using SeleniumExtras.PageObjects;
namespace UnitTestProject1
{
public class Base : SpecflowBaseTest
{
protected IWebDriver driver { get; set; }
public Base(IWebDriver Driver)
{
driver = Driver;
//PageFactory.InitElements(Driver, this);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TechTalk.SpecFlow;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using UnitTestProject1.Page;
using OpenQA.Selenium.Remote;
using BoDi;
namespace UnitTestProject1
{
[Binding]
public class SpecflowBaseTest : TechTalk.SpecFlow.Steps
{
// For additional details on SpecFlow hooks see
http://go.specflow.org/doc-hooks
protected IWebDriver Driver { get; set; }
private readonly IObjectContainer objectContainer;
[BeforeScenario]
public void BeforeScenario()
{
Driver = new ChromeDriver();
//this.objectContainer = objectContainer;
//ObjectContainer.RegisterInstanceAs<IWebDriver>(Driver);
Driver.Manage().Window.Maximize();
}
[AfterScenario]
public void AfterScenario()
{
Driver.Close();
Driver.Quit();
}
public void NavigateToURL(string URL)
{
Driver.Navigate().GoToUrl(URL);
}
protected LoginPage LoginPage => new LoginPage(Driver);
}
}
using NUnit.Framework;
using System;
using TechTalk.SpecFlow;
namespace UnitTestProject1.Steps
{
[Binding, Parallelizable]
public class LoginSteps : SpecflowBaseTest
{
[Given(#"I navigate to (.*)")]
public void GivenINavigateToHttpsCompany_Com(string URL)
{
NavigateToURL(URL);
}
[Given(#"I enter bw_(.*) and (.*)")]
public void GivenIEnterBw_Valid_UserAnd(string Username, string
Password)
{
LoginPage.Login(Username, Password);
}
[Then(#"I am logged in as bw_valid_user")]
public void ThenIAmLoggedInAsBw_Valid_User()
{
//LoginPage.
}
}
}
You need to initialize a new IWebDriver object and register it with SpecFlow's dependency injection framework in a [BeforeScenario].
[Binding]
public class SeleniumSpecFlowHooks
{
private readonly IObjectContainer container;
public SeleniumSpecFlowHooks(IObjectContainer container)
{
this.container = container;
}
[BeforeScenario]
public void CreateWebDriver()
{
// Create and configure a concrete instance of IWebDriver
IWebDriver driver = new FirefoxDriver(...)
{
...
};
// Make this instance available to all other step definitions
container.RegisterInstance(driver);
}
[AfterScenario]
public void DestroyWebDriver()
{
IWebDriver driver = container.Resolve<IWebDriver>();
driver.Close();
driver.Dispose();
}
}
Your step definition classes should not be initializing the web driver. Just declare an IWebDriver argument in their constructors.
Base class:
[Binding]
public class SpecflowBaseTest : TechTalk.SpecFlow.Steps
{
protected IWebDriver Driver { get; }
protected LoginPage LoginPage { get; }
public SpecflowBaseTest(IWebDriver driver)
{
Driver = driver;
LoginPage = new LoginPage(driver);
}
public void NavigateToURL(string URL)
{
Driver.Navigate().GoToUrl(URL);
}
}
Child class:
[Binding, Parallelizable]
public class LoginSteps : SpecflowBaseTest
{
[Given(#"I navigate to (.*)")]
public void GivenINavigateToHttpsCompany_Com(string URL)
{
NavigateToURL(URL);
}
[Given(#"I enter bw_(.*) and (.*)")]
public void GivenIEnterBw_Valid_UserAnd(string Username, string Password)
{
LoginPage.Login(Username, Password);
}
[Then(#"I am logged in as bw_valid_user")]
public void ThenIAmLoggedInAsBw_Valid_User()
{
//LoginPage.
}
}
solved by creating a new class
using BoDi;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using TechTalk.SpecFlow;
namespace DoclerQAtests
{
[Binding]
public class WebDriverSupport
{
private readonly IObjectContainer objectContainer;
private ChromeDriver webdriver;
public WebDriverSupport(IObjectContainer objectContainer)
{
this.objectContainer = objectContainer;
}
[BeforeScenario]
public void InitializeWebDriver()
{
this.webdriver = new ChromeDriver();
objectContainer.RegisterInstanceAs<IWebDriver>(webdriver);
}
}
}
For me this issue was resolved by adding a class level field public IWebDriver Driver instead of a local method level driver.
[Binding]
public class DriverSetup
{
private IObjectContainer _objectContainer;
public IWebDriver Driver;
public DriverSetup(IObjectContainer objectContainer)
{
_objectContainer = objectContainer;
}
[BeforeScenario]
public void BeforeScenario()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
var sauceOptions = new Dictionary<string, object>
{
["username"] = sauceUserName,
["accessKey"] = sauceAccessKey
};
var chromeOptions = new ChromeOptions
{
BrowserVersion = "latest",
PlatformName = "Windows 10"
};
chromeOptions.AddAdditionalOption("sauce:options", sauceOptions);
Driver = new RemoteWebDriver(new Uri("https://ondemand.saucelabs.com/wd/hub"),
chromeOptions.ToCapabilities(), TimeSpan.FromSeconds(30));
_objectContainer.RegisterInstanceAs(Driver);
}
}
Related
Trying to build integration test with connection to db in ServiceStack.
My ServiceStack app is working fine, but when I run simple test I got this error message in line:22
System.MissingMethodException: 'Method not found: 'Int32 ServiceStack.DataAnnotations.CustomFieldAttribute.get_Order()'.'
There is a lite cod:
using ServiceStack;
using ServiceStack.OrmLite;
using ServiceStack.Data;
using NUnit.Framework;
using ServiceStack.DataAnnotations;
using System.Collections.Generic;
namespace oth.Tests.IntegrationTests
{
public class AppHost2 : AppSelfHostBase
{
public AppHost2() : base("Customer REST Example", typeof(CustomerService).Assembly) { }
public override void Configure(Container container)
{
var connectionString = "Host=localhost;Port=5432;Database=test_1234;Username=postgres;Password=local";
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(connectionString, PostgreSqlDialect.Provider));
using var db = container.Resolve<IDbConnectionFactory>().Open();
db.CreateTableIfNotExists<Customer>();
}
}
public class Customer
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
[Route("/customers", "GET")]
public class GetCustomers : IReturn<GetCustomersResponse> { }
public class GetCustomersResponse
{
public List<Customer> Results { get; set; }
}
public class CustomerService : Service
{
public object Get(GetCustomers request)
{
return new GetCustomersResponse { Results = Db.Select<Customer>() };
}
}
public class CustomerRestExample
{
const string BaseUri = "http://localhost:2000/";
ServiceStackHost appHost;
public CustomerRestExample()
{
//Start your AppHost on TestFixture SetUp
appHost = new AppHost2()
.Init()
.Start(BaseUri);
}
[OneTimeTearDown]
public void OneTimeTearDown() => appHost.Dispose();
/* Write your Integration Tests against the self-host instance */
[Test]
public void Run_Customer_REST_Example()
{
var client = new JsonServiceClient(BaseUri);
var all = client.Get(new GetCustomers());
Assert.That(all.Results.Count, Is.EqualTo(0));
}
}
}
Anytime you see a missing type or missing method exceptions when using the MyGet pre-release packages it means you have a dirty installation (i.e. using pre-release packages from different build times).
In which case you'd need to Clear your Nuget packages cache and download the latest packages again, which ensures all your packages are from the latest same build:
$ dotnet nuget locals all -clear
I am creating a new Selenium framework using C#. Build is ok but tests failed due to the following error.
TearDown failed for test fixture Account.AddBankAccountFeature
BoDi.ObjectContainerException : Interface cannot be resolved:
TechTalk.SpecFlow.UnitTestProvider.IUnitTestRuntimeProvider('nunit')
TearDown : System.NullReferenceException : Object reference not set to
an instance of an object.
Here is my cs file
using System;
using TechTalk.SpecFlow;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using NUnit.Framework;
namespace Account
{
[Binding]
public class AddBankAccountSteps
{
IWebDriver driver = new ChromeDriver();
[Given(#"User is at the Login Page")]
public void GivenUserIsAtTheLoginPage()
{
driver.Url = "https://go.xxx.com/";
driver.Navigate().GoToUrl(driver.Url);
}
[When(#"User enter UserName and Password")]
public void WhenUserEnterUserNameAndPassword()
{
driver.FindElement(By.Id("email")).SendKeys("aa#ss.com");
driver.FindElement(By.Id("password")).SendKeys("aaa");
}
[When(#"User click on the LogIn button")]
public void WhenUserClickOnTheLogInButton()
{
driver.FindElement(By.Id("submitButton")).Click();
}
[Then(#"User can login in ")]
public void ThenUserCanLoginIn()
{
var expectedURL = "https://go.xxx.com/Dashboard/default.aspx";
var actualURL = driver.Url;
Assert.AreEqual(expectedURL, actualURL);
}
}
}
Thank you.
Question is probably really trivial but I cannot handle it in proper way. I'm using Selenium with NUnit, having two clases:
1) "DemoTest" which involves one simply test "DummyTest":
public class DemoTest : TestBase
{
public class RunTest
{
[Test, Category("Main-Tests"), Order(1)]
public void DummyTest()
{
}
}
}
2) "Test base" class where I want to place all of the NUnit/ driver attributes like: "SetUp" / "TearDown"
[TestFixture]
public class TestBase
{
public IWebDriver driver;
public IWebDriver Driver
{
get { return driver; }
set { driver = value; }
}
public string pageURL = "http://automationpractice.com/";
[SetUp]
public void SetUp()
{
driver = new ChromeDriver();
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(15);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(0);
driver.Navigate().GoToUrl(pageURL);
}
[TearDown]
public void TearDown()
{
driver.Close();
driver.Dispose();
}
}
}
As NUnit attributes are declared (SetUp section) my test from DemoTest class should at least move on the page under pageURL variable.
Result is that after running a test it's immediately jump on "passed" without opening the specified address.
"DemoTest" inherits from "Test base" class. Nuget packages are installed correctly. When I'm placing test inside the "Test base" class everything works correctly but I want to have it separated.
Try to fix DemoTest class as follows:
[TestFixture]
public class DemoTest : TestBase
{
[Test, Category("Main-Tests"), Order(1)]
public void DummyTest()
{
}
}
First sorry about my English.
Here is my problem:
I make a test for mantisbt with many test cases(report issue), so i put the login in [SetUpFixture] and in [TestFixture] [Test, TestCaseSource("function")] I don't know how to get driver which i use for creating chrome browser to get elements.
Here is my code:
namespace testcailz
{
[SetUpFixture]
public class TestsSetupClass
{
public void login(IWebDriver driver)
{
IWebElement username = driver.FindElement(By.Name("username"));
username.SendKeys("1353049");
IWebElement password = driver.FindElement(By.Name("password"));
password.SendKeys("123456");
IWebElement login = driver.FindElement(By.XPath("//input[#value='Login'][#class='button']"));
login.Click();
}
[SetUp]
public void GlobalSetup()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://www.cs.hcmus.edu.vn/mantisbt/login_page.php");
login(driver);
}
[TearDown]
public void GlobalTeardown()
{
// Do logout here
}
}
[TestFixture]
public class Class1
{
private static int[] data()
{
return new int[3] { 1, 2, 3 };
}
[Test, TestCaseSource("data")]
public void TestCaiLz(int i)
{
//wanna click to report new issue but how to get driver for Findelement
Assert.AreEqual(i, i);
}
}
}
As per java prospective, create driver object globally in class may be TestsSetupClass
public static WebDriver driver;
#BeforeSuite
public void startUp(){
driver=new FirefoxDriver();
driver.manage().window().maximize();
login(driver);
}
If you what to use this driver in another classes then extends this class. like below in java
public class Home extends Setup{ //...
}
Thank You,
Murali
I am trying to implement step-by-step selfhosting OWIN application following this article. I've done all examples before 'Use Configuration Objects for Configuring Middleware' section, but during coding the example from that section i've got error. Here my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
// Add the Owin Usings:
using Owin;
using Microsoft.Owin.Hosting;
using Microsoft.Owin;
namespace WebAPI
{
// use an alias for the OWIN AppFunc:
using AppFunc = Func<IDictionary<string, object>, Task>;
class Program
{
static void Main(string[] args)
{
WebApp.Start<Startup>("http://localhost:8080");
Console.WriteLine("Server Started; Press enter to Quit");
Console.ReadLine();
}
}
public class MyMiddlewareConfigOptions
{
string _greetingTextFormat = "{0} from {1}{2}";
public MyMiddlewareConfigOptions(string greeting, string greeter)
{
GreetingText = greeting;
Greeter = greeter;
Date = DateTime.Now;
}
public string GreetingText { get; set; }
public string Greeter { get; set; }
public DateTime Date { get; set; }
public bool IncludeDate { get; set; }
public string GetGreeting()
{
string DateText = "";
if (IncludeDate)
{
DateText = string.Format(" on {0}", Date.ToShortDateString());
}
return string.Format(_greetingTextFormat, GreetingText, Greeter, DateText);
}
}
public static class AppBuilderExtensions
{
public static void UseMyMiddleware(this IAppBuilder app, MyMiddlewareConfigOptions configOptions)
{
app.Use<MyMiddlewareComponent>(configOptions);
}
public static void UseMyOtherMiddleware(this IAppBuilder app)
{
app.Use<MyOtherMiddlewareComponent>();
}
}
public class MyMiddlewareComponent
{
AppFunc _next;
// Add a member to hold the greeting:
string _greeting;
public MyMiddlewareComponent(AppFunc next, string greeting)
{
_next = next;
_greeting = greeting;
}
public async Task Invoke(IDictionary<string, object> environment)
{
IOwinContext context = new OwinContext(environment);
// Insert the _greeting into the display text:
await context.Response.WriteAsync(string.Format("<h1>{0}</h1>", _greeting));
await _next.Invoke(environment);
}
}
public class MyOtherMiddlewareComponent
{
AppFunc _next;
public MyOtherMiddlewareComponent(AppFunc next)
{
_next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
IOwinContext context = new OwinContext(environment);
await context.Response.WriteAsync("<h1>Hello from My Second Middleware</h1>");
await _next.Invoke(environment);
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Set up the configuration options:
var options = new MyMiddlewareConfigOptions("Greetings!", "John");
options.IncludeDate = true;
// Pass options along in call to extension method:
//app.UseMyMiddleware(options);
app.Use<MyMiddlewareComponent>(options);
app.UseMyOtherMiddleware();
}
}
}
The class 'WebAPI.MyMiddlewareComponent' does not have a constructor taking 2 arguments.
when app.Use<MyMiddlewareComponent>(options); is calling. If i use some string instead of MyMiddlewareConfigOptions:
app.Use<MyMiddlewareComponent>("somestring");
it works.
Version of Owin package is 3.0.1.0, .NET Framework - 4.5.
Why it is happening?
Oh, i figured it out... It was article's mistake: this part in MyMiddlewareComponent class
public MyMiddlewareComponent(AppFunc next, string greeting)
{
_next = next;
_greeting = greeting;
}
should be replaced by that
public MyMiddlewareComponent(AppFunc next, MyMiddlewareConfigOptions options)
{
_next = next;
_greeting = options.GetGreeting();
}
Now it works.