Cannot create an instance for Expected Condition class in C# Selenium - selenium

When I try to create an instance for Expected Condition class it throws an error
ExpectedConditions obj = new ExpectedConditions();
The error I'm getting here is "Has no Constructors defined".
ExpectedConditions is a sealed class. And the method reside inside the sealed class are static methods.
In C# class, by default there is a constructor. Only the static classes doesn't have a default constructor.
So I have tried a small example
public sealed class A
{
public static string GetName()
{
return "name";
}
public static int GetID()
{
return 1;
}
public string Name()
{
return "aa";
}
}
//Sealed class with static methods
B obj2 = new B();
B.GetName();
B.GetID();
obj2.Name();
Build Succeeded
In my example code, It's possible to create an object for the sealed class and can be able to access the methods.
Why it is not possible to create an object with default constructor
ExpectedConditions obj = new ExpectedConditions();
for the ExpectedCondition class in C# Selenium? Why it is throwing an error when instantiating?

Some notes before:
The sealed modifier is used for a class to prevent other classes to inherit from it.
static classes do have a static constructor that is called automatically to initialize the class before the first instance is created or any static members are referenced. However, the constructor cannot be called directly. You can read more on the topic here.
Now, to get on the subject, you cannot instantiate the ExpectedConditions class because it's constructor is private. You can only use the it's static methods.
An example would be to find an element by ID and wait until it is clickable:
var wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));
var clickableElement = wait.Until(ExpectedConditions.ElementIsClickable(By.Id("id")));
You can see the implementation of the ExpectedConditions class here.
Github location of the ExpectedConditions class is here.

Related

Cannot extend generic interface in Groovy

I am trying to implement a spring interface called the ObjectPostProcessor interface in groovy to create a new class.
I have tried to do it using a new class implementing the interface and also by creating a new anonymous class. I keep seeing an error saying.
Groovyc: Can't have an abstract method in a non-abstract class.
Which makes me think that groovy doesn't consider the abstract method of the class as overriden correctly.
Below is the code example that is breaking.
What is the correct way to implement this kind of an interface in groovy ?
interface ObjectPostProcessor<T> {
/**
* Initialize the object possibly returning a modified instance that should be used
* instead.
*
* #param object the object to initialize
* #return the initialized version of the object
*/
public <O extends T> O postProcess(O object);
}
// groovy error Error:(15, 1) Groovyc: Can't have an abstract method in a non-abstract class. The class 'ObjectPostProcessorImpl' must be declared abstract or the method 'java.lang.Object postProcess(java.lang.Object)' must be implemented.
class ObjectPostProcessorImpl implements ObjectPostProcessor<Integer> {
#Override
public <O extends Integer> O postProcess(O object) {
return object
}
}
class Anon {
public static void main(String[] args) {
ObjectPostProcessor<Integer> objectPostProcessor = new ObjectPostProcessor<Integer>() {
/** Groovyc: Can't have an abstract method in a
* non-abstract class.
* The class 'ObjectPostProcessorImpl' must
* be declared abstract or the method
* 'java.lang.Object postProcess(java.lang.Object)'
* must be implemented. */
#Override
public <O extends Integer> O postProcess(O object) {
return object;
}
};
ObjectPostProcessorImpl objectPostProcessorImplObj = new ObjectPostProcessorImpl();
System.out.println(objectPostProcessor.postProcess(12));
System.out.println(objectPostProcessorImplObj.postProcess(12));
}
}

What is the difference between 'open' and 'public' in Kotlin?

I am new to Kotlin and I am confused between open and public keywords. Could anyone please tell me the difference between those keywords?
The open keyword means “open for extension“ - i.e. it's possible to create subclasses of an open class:
The open annotation on a class is the opposite of Java's final: it allows others to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Effective Java, Item 17: Design and document for inheritance or else prohibit it.
You also need to be explicit about methods you want to make overridable, also marked with open:
open class Base {
open fun v() {}
fun nv() {}
}
The public keyword acts as a visibility modifier that can be applied on classes, functions, member functions, etc. If a top-level class or function is public, it means it can be used from other files, including from other modules. Note that public is the default if nothing else is specified explicitly:
If you do not specify any visibility modifier, public is used by default, which means that your declarations will be visible everywhere
class A { ... } in Java is equal to open class A { ... } in Kotlin.
final class B { ... } in Java is equal to class B { ...} in Kotlin.
It is not related with public.
In Kotlin, everything without access modifiers is public by default. You can explicitly say public in the definition, but it is not necessary in Kotlin.
So,
public class A { ... }
and
class A { ... }
are the same in Kotlin.
I put here just for my memo, maybe useful for someone else :
open class in kotlin means that a class can be inherited because by default they are not:
class Car{....}
class Supercar:Car{....} : // give an error
open Car2{....}
class Supercar:Car2{....} : // ok
public class in Java is about the visibility of class (nothing to do with inheritance : unless a class in java is final, it can be inherited by default).
In kotlin all the class are public by default.
open method in kotlin means that the method can be overridden, because by default they are not.
Instead in Java all the methods can be overridden by default
The method of an open class cannot be overridden by default as usual (doesn't matter if the class is open), they must be declared that they can be overridden :
open class Car{
fun steering{...}
}
class Supercar:Car{
override fun steering {...} // give an error
}
open class Car2{
open fun steering{...}
}
class Supercar:Car2{
override fun steering {...} // ok
}
for more details : https://kotlinlang.org/docs/reference/classes.html
public: public keyword in Kotlin is similar to java it is use to make the visibility of classes, methods, variables to access from anywhere.
open: In Kotlin all classes, functions, and variables are by defaults final, and by inheritance property, we cannot inherit the property of final classes, final functions, and data members. So we use the open keyword before the class or function or variable to make inheritable that.
open is opposite to Final in java.
If the class is not 'open', it can't be inherited.
class First{}
class Second:First(){} // Not allowed. Since 'First' is Final(as in Java) by default. Unless marked "open" it can't be inherited
Don't get confused with open and public. public is a visibility modifier
class Third{} // By default this is public
private class Fourth{}
class Fifth{
val third = Third() // No issues
val fourth = Fourth() // Can't access because Fourth is private
}
All classes, methods, and members are public by default BUT not open
Keyword open in kotlin means "Open for Extension"
means if you want any class to be inherited by any subclass or method to be overriden in subclasses you have to mark as open otherwise you will get compile time error
NOTE: abstract classes or methods are open by default you do not need to add explicitly.
OPEN VS FINAL VS PUBLIC
OPEN :
child class can access this because they are inherited by its parent.
In Kotlin you need to add 'open' keyword unlike java whose all classes are 'open' by default
Example :
Kotlin : open class A () {}
Java : class A () {}
FINAL :
child class can't access or inherit.
In JAVA you need to add 'final' keyword unlike kotlin whose all classes are 'final' by default
Example :
Kotlin : class A () {}
Java : final class A () {}
PUBLIC : Any class whether its inherited or not can access its data or methods.
Example in Kotlin :
//Final
class DemoA() {
protected fun Method() {
}
}
class DemoB() : DemoA {
Method() // can't access
}
//OPEN
open class DemoA() {
protected fun Method() {
}
}
class DemoB() : DemoA {
Method() // can access
}
//Public
class DemoA() {
fun Method() {
}
}
class DemoB() {
val a = DemoA()
a.Method() // can access
}
Example in Java :
//FINAL
final class DemoA() {
protected void name() {
}
}
class DemoB() extends DemoA {
name(); // Can't access
}
//Open
class DemoA() {
protected void name() {
}
}
class DemoB() extends DemoA {
name(); // Can access
}
//Public
class DemoA() {
void name() {
}
}
class DemoB(){
DemoA a = new DemoA()
a.name(); // Can access
}
Summarized answer (Kotlin)
The defaults of declarations of classes, methods, and properties are
(public + final). final prevents any inheritance attempts.
In order to be able to extend a class, you must mark the
parent class with the open keyword.
In order to be able to override the methods or properties, you must
mark them in the parent class with the open keyword, in addition to
marking the overriding method or parameter with the override keyword.
public is just encapsulation, it affects the visibility of classes/ methods. Public will make them visible everywhere.
Reference

Avoiding instance construction of return type while generating stub for method

I have issue while trying to mock method that returns instance of abstract class with Rhino Mocks. Issue is that MammalBase constructor is invoked while stub is created and I would like to avoid that. All source code in question is locked for editing and only tests can be changed.
Eventually, base class is processing something by type attributes in constructor, and throws exception if no adequate attributes are detected. That causes a extensive logging.
My hope is to remove unnecessary logs from tests.
Is it possible to instruct Rhino Mocks not to instantiate return type (MammalBase) when it creates proxy while creating a stub?
Is explicit attribute or type setting possible for return value while Rhino creates stub for method with abstract class instance as return type?
Is avoiding constructor even possible without making stubbed method return interface?
I found that issue does not exist if:
1. Stubbed method returns array like MammalBase[],
2. Stubbed method returns derivate class like "Human" first, since no more constructors of base class are invoked.
Thanks in advance!
(Code sample)
public interface IDetermineMammalByType
{
MammalBase DetermineMammalByType(MammalBase creature);
}
public abstract class MammalBase
{
protected MammalBase()
{
CustomAttribute[] attributes = (CustomAttribute[])Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute));
if (!attributes.Any(x=> x as CustomAttribute != null))
{
//This causes issue
throw new Exception();
}
}
}
[CustomAttribute()]
public class Human : MammalBase { }
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)]
public class CustomAttribute : System.Attribute
{
public CustomAttribute() { }
}
public class MammalDetector : IDetermineMammalByType
{
public MammalBase DetermineMammalByType(MammalBase creature)
{
//Some logic
return null;
}
}
//TEST
[TestMethod()]
public void DetermineMammalByTypeTest()
{
IDetermineMammalByType myTest = MockRepository.GenerateStub<IDetermineMammalByType>();
var creature = new Human();
//Here it fails while mocking method
myTest.Stub(x => x.DetermineMammalByType(creature)).Return(new Human());
}

how to ensure only one instance of singleton class is created?

I have read the concepts of Singleton design pattern and understood that for making a class singleton we have to do the following steps :
1)Private constructor to restrict instantiation of the class from other classes.
2)Private static variable of the same class that is the only instance of the class.
3)Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
So my class looks like this :
public class Singleton {
private static Singleton singleton =new Singleton();;
/* A private Constructor prevents any other
* class from instantiating.
*/
private Singleton(){
System.out.println("Creating new now");
}
/* Static 'instance' method */
public static Singleton getInstance( ) {
return singleton;
}
/* Other methods protected by singleton-ness */
public void demoMethod( ) {
System.out.println("demoMethod for singleton");
}
}
But here how we can ensure that only one instance of Singleton is created ? Suppose I have 2 classes Singletondemo1 and Singletondemo2.
In Singletondemo1 , I am calling the getInstance() and craete an object. Same way I can do that in Singletondemo2 also.
So how we will ensure only object is created and also it is thread safe.

Jackson mixin selection and inheritance

I have a problem with Jackson mixin and inheritance. I have two target classes, a parent and a child. For those two target classes I have defined two MixIn classes (interfaces) with no inheritance relationship with each other. I also tested with one MixIn interface extending the other but there was no difference in the outcome. When Jackson serializes the parent class it uses the correctly defined mixin for the serialization config and everything works well. However when Jackson serializes the child class it will use the parent class mixin definitions for serializing properties that exist in both the parent and the child class. Then it uses the child class mixin definitions for serializing the properties defined in the child class but not in the parent class. Now this probably has something to do with comparing the base classes or implementing interfaces in Jackson.
Now the question is that is there any way that I could instruct Jackson to use only the mixin definitions for the child class when serializing objects of the child class? And yes I would like to keep both the the mixin definitions in place for two separate use cases so just removing the parent class mixin mapping is not gonna solve my issue.
Example code and expected and actual output JSONs below.
Environment:
Jackson version 2.1.4
Tomcat version 7.0.34.0
Target classes and interfaces they implement:
public interface TestI {
public String getName();
}
public interface TestExtendI extends TestI {
public Integer getAge();
}
public class Test implements TestI {
String name;
public Test(String name) {
this.name = name;
}
#Override
public String getName() {
return name;
}
}
public class TestExtend extends Test implements TestExtendI {
private Integer age;
public TestExtend(String name) {
super(name);
}
public TestExtend(String name, Integer age) {
super(name);
this.age = age;
}
#Override
public Integer getAge() {
return age;
}
}
Mixins definitions
public interface TestMixIn {
#JsonProperty("base-name")
public String getName();
}
public interface TestExtendMixIn {
#JsonProperty("ext-name")
public String getName();
#JsonProperty("ext-age")
public Integer getAge();
}
If both mixins are added to the mapper the output JSON is:
{
"base-name": "5", // from parent class mixin definition
"ext-age": 50 // from child class mixin defition
}
With mixin for TestI.class commented everything works as expected and the output JSON is (this is what I would like to achieve):
{
"ext-name": "5", // from child class mixin defition
"ext-age": 50 // from child class mixin defition
}
Object mapper configuration
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JacksonObjectMapper implements ContextResolver<ObjectMapper> {
private ObjectMapper mapper;
public JacksonObjectMapper() {
mapper = new ObjectMapper();
mapper.addMixInAnnotations(TestI.class, TestMixIn.class);
mapper.addMixInAnnotations(TestExtendI.class, TestExtendMixIn.class);
}
public ObjectMapper getContext(Class<?> type) {
return this.mapper;
}
}
REST api for handling the request/response
#Path("api/test/{id}")
public class TestRestApi {
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public TestI getTest(#PathParam("id") String id) {
TestI ret = new TestExtend(id, 50);
return ret;
}
}
Solution
As described by pgelinas in the first response the solution to this problem is to define the methods that should be handled by the 'child' mixin again in the child interface. For the example code above that would mean changes to the TestExtendI interface:
public interface TestExtendI extends TestI {
public Integer getAge();
// override the method from the parent interface here
#Override
public String getName();
}
This will solve the issue and doesn't add too much boilerplate code to the solution. Moreover it will not change the interface contracts since the child interface already extends the parent interface.
This is a tricky one; the answer to your specific question is no, you cannot tell a child class to not use the Mixin applied to a parent class.
However, a simple solution to your problem here is to re-declare the getName() method in the TestExtendI interface. I believe MixIn annotation resolution doesn't follow the usual parent-child override (as is the case with normal annotations), but will instead prefer the MixIn that is applied to the class that declares the method. This might be a bug in Jackson or a design choice, you can always fill an issue on github.