In Page Class should the action methods have return type as class name or using void return type is a good practice? - selenium

public class HomePage {
public HomePage clickAboutUs1Link() {
aboutUs1.click();
return this;
}
public void clickAboutUs1Link() {
aboutUs1.click();
}
}
I will be calling the action method in my Test Class. So is there any advantage or disadvantage of using any one over the other when using Page Object Model with Selenium webdriver?

This question will be more clear if you had more methods. Consider those classes
public class HomePage {
public AboutUsPage clickAboutUsLinkAndGoToAboutUsPage() {
aboutUs1.click();
return new AboutUsPage();
}
public HomePage typeToField() {
aboutUs1.click();
return this;
}
public HomePage clickOnChecbox() {
aboutUs1.click();
return this;
}
}
class AboutUsPage {
public boolean isAboutUsPageDisplayed() {
return someElement.isDisplayed();
}
}
Now you can use method chaining in the test to create a flow
public class TestAboutUsLink {
boolean isDisplayed =
new HomePage()
.typeToField()
.clickOnChecbox()
.clickAboutUsLinkAndGoToAboutUsPage()
.isAboutUsPageDisplayed();
assertTrue(isDisplayed);
}
And if every method didn't return anything
public class TestAboutUsLink {
HomePage homePage = new HomePage();
homePage.typeToField();
homePage.clickOnChecbox();
homePage.clickAboutUsLinkAndGoToAboutUsPage()
AboutUsPage aboutUsPage = new AboutUsPage();
boolean isDisplayed = aboutUsPage.isAboutUsPageDisplayed();
assertTrue(isDisplayed);
}
This is subjective issue, but I find it clearer to have the test flow with implicit page objects creation (as far as the test concern) than breaking it to parts.

Related

How do you adjust json config in Quarkus?

I am attempting to add a mixin to the Jackson's ObjectMapper in a Quarkus project. I have some code that looks likes this:
#Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
this.mapper = createObjectMapper();
}
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(MyModel.class, MyMixin.class);
return mapper;
}
}
This code worked perfectly in a Thorntail project I had. For some reason, Quarkus isn't picking this up, and the object mapper is not affected. Is there something different I have to do with the Quarkus CDI?
Updates
Apparently I was a little confused about the implementation. I should be using the Json-B api. I figured out how to change the configuration for Json-B and posted it below.
Instead of providing an ObjectMapper, you can provide a JsonbConfig so that you can customize serialization/deserialization.
Here is what I ended up using:
#Provider
public class JsonConfig implements ContextResolver<Jsonb> {
#Override
public Jsonb getContext(Class type) {
JsonbConfig config = new JsonbConfig();
config.withPropertyVisibilityStrategy(new IgnoreMethods());
return JsonbBuilder.create(config);
}
}
class IgnoreMethods implements PropertyVisibilityStrategy {
#Override
public boolean isVisible(Field field) {
return true;
}
#Override
public boolean isVisible(Method method) {
return false;
}
}
This allows you to customize your JsonbConfig. Here, mine specifically prevents access of methods for serialization/deserialization. On Quarkus with Panache, this prevents isPersistent from appearing in your JSON output.
In addition to the correct answer of #jsolum, here is a working provider which uses the fasterxml-annotations to check visibility of fields and methods:
#Provider
public class JsonConfig implements ContextResolver<Jsonb> {
#Override
public Jsonb getContext(Class aClass) {
JsonbConfig config = new JsonbConfig();
config.withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {
#Override
public boolean isVisible(Field field) {
JsonIgnore annotation = field.getAnnotation(JsonIgnore.class);
return annotation == null || !annotation.value();
}
#Override
public boolean isVisible(Method method) {
JsonIgnore annotation = method.getAnnotation(JsonIgnore.class);
return annotation == null || !annotation.value();
}
});
return JsonbBuilder.create(config);
}
}
JsonbConfig in Quarkus can be customized providing an ApplicationScoped instance of JsonbConfigCustomizer (taking #jsolum's answer into account):
#ApplicationScoped
public class JsonbFormattingConfig implements JsonbConfigCustomizer {
#Override
public void customize(JsonbConfig jsonbConfig) {
jsonbConfig.withPropertyVisibilityStrategy(new IgnoreMethods());
}
}
class IgnoreMethods implements PropertyVisibilityStrategy {
#Override
public boolean isVisible(Field field) {
return true;
}
#Override
public boolean isVisible(Method method) {
return false;
}
}
Source: https://quarkus.io/guides/rest-json#json-b

Opening different URLs in one Serenity task class?

In Serenity BDD I have a Task which opens the login page of an application. I'd like to use this class to not only open the login page but other pages as well.
public class StartWith implements Task {
LoginPage loginPage;
#Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Open.browserOn(loginPage)
);
}
public static Task theLoginPage() {
return instrumented(StartWith.class);
}
// Is this possible???
public static Task theContactPage() {
return instrumented(StartWith.class);
}
}
Is it possible to add another static method e.g. theContactPage so that my actor could call one of these:
StartWith.theLoginPage()
StartWith.theContactPage()
You can use url as string param.
public class StartWith implements Task {
private final String url;
public StartWith(String url) {
this.url = url;
}
#Override
#Step("{0} start portal at \\{#url\\}")
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Open.url(url)
);
}
public static Task theLoginPage() {
String url = "http://example.com/login";
return instrumented(StartWith.class, url);
}
public static Task theContactPage() {
String url = "http://example.com/contact";
return instrumented(StartWith.class);
}
}

How to use #DataProvider present in different class

How to use #DataProvider that is present in a different class?
I have created a different package and I have defined data providers next to each test cases. Please share how I may to use that in a different class.
You can use the dataProviderClass attribute of #Test:
public class StaticProvider {
#DataProvider(name = "create")
public static Object[][] createData() {
return new Object[][] {
new Object[] { new Integer(42) }
};
}
}
public class MyTest {
#Test(dataProvider = "create", dataProviderClass = StaticProvider.class)
public void test(Integer n) {
// ...
}
}
Check the documentation for more details.
If you have unique dataProvider method name (createData), and if you choose not to give name after DataProvider annotation as below,
#DataProvider
public Object[][] createData(){
}
Then you can use the method name as below,
#Test(dataProvider = "createData", dataProviderClass = StaticProvider.class)

Is it possible to use one generic/abstract service in ServiceStack?

I am developing a (hopefully) RESTful API using ServiceStack.
I noticed that most of my services look the same, for example, a GET method will look something like this:
try
{
Validate();
GetData();
return Response();
}
catch (Exception)
{
//TODO: Log the exception
throw; //rethrow
}
lets say I got 20 resources, 20 request DTOs, so I got about 20 services of the same template more or less...
I tried to make a generic or abstract Service so I can create inheriting services which just implement the relevant behavior but I got stuck because the request DTOs weren't as needed for serialization.
Is there any way to do it?
EDIT:
an Example for what I'm trying to do:
public abstract class MyService<TResponse,TRequest> : Service
{
protected abstract TResponse InnerGet();
protected abstract void InnerDelete();
public TResponse Get(TRequest request)
{
//General Code Here.
TResponse response = InnerGet();
//General Code Here.
return response;
}
public void Delete(TRequest request)
{
//General Code Here.
InnerDelete();
//General Code Here.
}
}
public class AccountService : MyService<Accounts, Account>
{
protected override Accounts InnerGet()
{
throw new NotImplementedException();//Get the data from BL
}
protected override void InnerDelete()
{
throw new NotImplementedException();
}
}
To do this in the New API we've introduced the concept of a IServiceRunner that decouples the execution of your service from the implementation of it.
To add your own Service Hooks you just need to override the default Service Runner in your AppHost from its default implementation:
public virtual IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
return new ServiceRunner<TRequest>(this, actionContext); //Cached per Service Action
}
With your own:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(ActionContext actionContext)
{
return new MyServiceRunner<TRequest>(this, actionContext); //Cached per Service Action
}
Where MyServiceRunner is just a custom class implementing the custom hooks you're interested in, e.g:
public class MyServiceRunner<T> : ServiceRunner<T> {
public override void OnBeforeExecute(IRequestContext requestContext, TRequest request) {
// Called just before any Action is executed
}
public override object OnAfterExecute(IRequestContext requestContext, object response) {
// Called just after any Action is executed, you can modify the response returned here as well
}
public override object HandleException(IRequestContext requestContext, TRequest request, Exception ex) {
// Called whenever an exception is thrown in your Services Action
}
}
Also for more fine-grained Error Handling options check out the Error Handling wiki page.
My solution was to add an additional layer where I can handle Logic per entity:
Base Logic Sample:
public interface IEntity
{
long Id { get; set; }
}
public interface IReadOnlyLogic<Entity> where Entity : class, IEntity
{
List<Entity> GetAll();
Entity GetById(long Id);
}
public abstract class ReadOnlyLogic<Entity> : IReadOnlyLogic<Entity> where Entity : class, IEntity, new()
{
public IDbConnection Db { get; set; }
#region HOOKS
protected SqlExpression<Entity> OnGetList(SqlExpression<Entity> query) { return query; }
protected SqlExpression<Entity> OnGetSingle(SqlExpression<Entity> query) { return OnGetList(query); }
#endregion
public List<Entity> GetAll()
{
var query = OnGetList(Db.From<Entity>());
return Db.Select(query);
}
public Entity GetById(long id)
{
var query = OnGetSingle(Db.From<Entity>())
.Where(e => e.Id == id);
var entity = Db.Single(query);
return entity;
}
}
Then we can use hooks like:
public interface IHello : IReadOnlyLogic<Hello> { }
public class HelloLogic : ReadOnlyLogic<Hello>, IHello
{
protected override SqlExpression<Hello> OnGetList(SqlExpression<Hello> query)
{
return query.Where(h => h.Name == "Something");
}
}
Finally our service only calls our logic:
public class MyServices : Service
{
IHello helloLogic;
public object Get()
{
return helloLogic.GetAll();
}
}

SpecFlow + Selenium-WebDriver: Sharing a WebDriver Across Steps?

Say I have a scenario that uses steps that are contained in two different classes. Is there a way for both of them to have a handle to the same IWebDriver instance without going through ScenarioContext.Current["webdriverVariableName"]?
That's so ugly. Is there a cleaner way?
I was going to make a class with a public static IWebDriver property that gets assigned at the start of every scenario, so that all my steps could refer to it, but I don't think that will work when I start to run them in parallel, as each scenario would overwrite the global driver.
Specflow offers a Dependency Injection mecanism, so you could get your web driver instance injected in your steps.
See https://github.com/techtalk/SpecFlow/wiki/Context-Injection
See the "Avanced options" section.
I have just started using Specflow but this appears to work;
Create a class which takes IObjectContainer as a constructor and has a BeforScenario method to create the WebDriver instance;
[Binding]
public class WebDriverSupport
{
private readonly IObjectContainer _objectContainer;
public WebDriverSupport(IObjectContainer objectContainer)
{
_objectContainer = objectContainer;
}
[BeforeScenario]
public void InitializeWebDriver()
{
var webDriver = DriverFactory.CreateDriver();
_objectContainer.RegisterInstanceAs<RemoteWebDriver>(webDriver);
}
}
Create your step classes with a constructor which take RemoteWebDriver;
[Binding]
public class POCSteps
{
private readonly IdlWebDriver _driver;
public POCSteps(IdlWebDriver driver)
{
_driver = driver;
}
}
Your steps steps will now have access to a fully instantiated WebDriver object
My tests, which are currently working fine running multithreaded webdriver instances, are using a base step definitions class to hold the driver instance. All step definitions inherit from this, so the driver is available to all steps..
namespace Project.StepDefinitions
{
[Binding]
public class BaseStepDefinitions
{
private const string CurrentPageKey = "Current.Page";
public static IWebDriver Driver { get; set; }
protected LogonPageModel LogonPage
{
get { return (LogonPageModel)ScenarioContext.Current[CurrentPageKey]; }
set { ScenarioContext.Current[CurrentPageKey] = value; }
}
protected RegisterPageModel RegisterPage
{
get { return (RegisterPageModel)ScenarioContext.Current[CurrentPageKey]; }
set { ScenarioContext.Current[CurrentPageKey] = value; }
}
}
}
//////////////
namespace SpecDriver.StepDefinitions
{
[Binding]
public class LoginSteps : BaseStepDefinitions
{
[Given(#"I navigate to the homepage")]
public void GivenINavigateToTheHomepage()
{
Driver.Navigate().GoToUrl(SettingsManager.BaseUrl);
}
}
}
etc etc...
Just create a new separated class with a static property that returns driver:
static class DriverProvider
{
private static IWebDriver _driver;
public static IWebDriver Driver
{
get
{
if (_driver == null)
{
_driver = new ChromeDriver();
_driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(40);
_driver.Manage().Window.Maximize();
}
return _driver;
}
}
}
Each time you will need to do something with driver, just call it in a such way:
SomeMethod(DriverProvider.Driver);
//
IWebelement e = DriverProvider.Driver.FindElement(By.XPath("you_XPath"));
e.Click();
// etc etc etc