whenNew() with PoweMockito - junit4

I have mocked File class constructor with PowerMockito.
PowerMockito.whenNew(File.class).withArguments("Filepath").thenReturn(mockFile);
But when my sut class create File("withSomeOtherPath"), null is returned.
I expect 'mockFile' should be returned, when called with "Filepath" argument, with other argument actual constructor should be called.
Isn't it true?

"I expect 'mockFile' should be returned, when called with "Filepath" argument, with other argument actual constructor should be called." ---->This is true of Spy not Mock.
Default behaviour with Spy is to call real method unless it is stubbed.
Where as with Mock the default behaviour is do Nothing when not stubbed. Hence you got null.
Try this
PowerMockito.whenNew(File.class).withArguments("Filepath").thenReturn(mockFile).thenCallRealMethos();

Related

Syntax of call to super class constructor

Within a subclass constructor, what is the difference between calling obj#SuperClass(a,b); and obj = obj#SuperClass(a,b);
Both are found in doc, for ex. here
The canonical syntax for calling a superclass constructor is
obj = obj#SuperClass(args)
(see the documentation).
This is comparable to calling any constructor, where the output of the function call is assigned to a variable:
obj = SuperClass(args)
However, because the superclass constructor must initialize fields inside a (larger) derived object, the obj to be modified must be passed in some way to the function call, hence the (awkward) obj# syntax.
But because we pass the object to be initialized, which is modified, we don’t really need to capture that output any more. Hence the other form,
obj#SuperClass(args)
does exactly the same things in all situations I have encountered.
There is no difference that I can see. I would be surprised if the first syntax did any data copying whatsoever, that has most certainly been optimized out, just like obj = obj.method(args) doesn’t copy the object.

Why direct usage of generic value is not possible but same is possible if returned from method in Dart

Why is it assigning a value to a generic field is not possible when assigned directly, but same is possible when using a variable reference or method return value (here, same value is assigned to the variable and method returns the same value)?
class User {}
class Teacher extends User {}
class Student extends User {}
Future<User> getUser() {
return Future.value(Student());
}
void main() {
Future<Future<User>> fut = Future.value(getUser()); // <----- No error
Future<Future<User>> fut2 = Future.value(Future.value(Student())); // <----- Getting error
Future<User> userFut3 = Future.value(Student());
Future<Future<User>> fut3 = Future.value(userFut3); // <----- No error
}
Getting below error when Future.value(Future.value(Student())) assigned directly.
Error: The argument type 'Student' can't be assigned to the parameter type 'FutureOr<Future<User>>?'.
The issue here is that the parameter of Future<T>.value has the type FutureOr<T>. It can be either a future or a value.
Also, Dart type inference works by "pushing down" a context type, then trying to make the expression work at that type, and finally pushing the final static type back up.
If an expression like Future.value(...) has a context type, the missing type argument is always inferred from the context type.
When you write
Future<Future<User>> fut2 = Future.value(Future.value(Student()));
the context type of the outer Future.value, the type we know it should have, is Future<Future<User>>. That makes its argument have context type FutureOr<Future<User>>.
The argument is Future.value(Student()), where we don't yet know anything about Student() because we haven't gotten to it in the type inference yet, we're still working out way down towards it.
A Future<X> can satisfy that FutureOr<Future<User>> in two ways, either by being a Future<User> or by being a Future<Future<User>>.
Type inference then guesses that it's the latter. It's wrong, but it can't see that yet. The way type inference works, it has to use the context type when there is one, but the context type is ambiguous, and it ends up choosing the wrong option.
You are hitting an edge case of the type inference where the context type can be satisfied in two different ways, and the downwards type inference chooses the wrong one. It's a good heuristic that if you have a FutureOr<...> context type, and you see a Future constructor, you want the Future-part of the FutureOr<...>. It breaks down when you have FutureOr<Future<...>>. So, don't do that!
My recommendation, in complete generality, is to never have a Future<Future<anything>> in your program. Not only does it avoid problems like this, but it's also a better model for your code.
A future which eventually completes to something which eventually completes to a value ... just make it eventually complete to that value directly. Waiting for the intermediate future is just needless busywork.
Because in the function you defined the return type and dart knows the return type, but when assigning directly dart does not know Future.value(Student()) has a type of Future<User>. to fix this you have to tell the dart the type of the value, like this: Future.value((Future.value(Student())) as Future<User>);
this way dart will know the type of this value and treat it as a Future<User>.

Error when inheriting from Ektron.Cms.Content.Targeting.Rules.RuleTemplate

I have a C# class called MyCustomRuleTemplate which is inherited from Ektron.Cms.Content.Targeting.Rules.RuleTemplate class. In that I have added a constructor such as below
public MyCustomRuleTemplate(): base("someKey")
{
//Some code here
}
Its working fine without any error. If I given it as
public MyCustomRuleTemplate()
{
//Some code here
}
Im getting error like 'Ektron.Cms.Content.Targeting.Rules.RuleTemplate' does not contain a constructor that takes 0 arguments.
Can anybody help me to know why it is?
The reason you are seeing "does not contain a constructor that takes 0 arguments" when instantiating your class object using the second constructor is because when you call your constructor, c# tries to call the constructor on the base class as well, which in this case takes a parameter.
See this post on msdn:
http://msdn.microsoft.com/en-us/library/ms173115%28v=vs.80%29.aspx
Key parts:
"In this example, the constructor for the base class is called before the block for the constructor is executed. The base keyword can be used with or without parameters. Any parameters to the constructor can be used as parameters to base, or as part of an expression. For more information, see base.
In a derived class, if a base-class constructor is not called explicitly using the base keyword, then the default constructor, if there is one, is called implicitly."
And: "If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor using base."

Usages of Null / Nothing / Unit in Scala

I've just read: http://oldfashionedsoftware.com/2008/08/20/a-post-about-nothing/
As far as I understand, Null is a trait and its only instance is null.
When a method takes a Null argument, then we can only pass it a Null reference or null directly, but not any other reference, even if it is null (nullString: String = null for example).
I just wonder in which cases using this Null trait could be useful.
There is also the Nothing trait for which I don't really see any more examples.
I don't really understand either what is the difference between using Nothing and Unit as a return type, since both doesn't return any result, how to know which one to use when I have a method that performs logging for example?
Do you have usages of Unit / Null / Nothing as something else than a return type?
You only use Nothing if the method never returns (meaning it cannot complete normally by returning, it could throw an exception). Nothing is never instantiated and is there for the benefit of the type system (to quote James Iry: "The reason Scala has a bottom type is tied to its ability to express variance in type parameters."). From the article you linked to:
One other use of Nothing is as a return type for methods that never
return. It makes sense if you think about it. If a method’s return
type is Nothing, and there exists absolutely no instance of Nothing,
then such a method must never return.
Your logging method would return Unit. There is a value Unit so it can actually be returned. From the API docs:
Unit is a subtype of scala.AnyVal. There is only one value of type
Unit, (), and it is not represented by any object in the underlying
runtime system. A method with return type Unit is analogous to a Java
method which is declared void.
The article you quote can be misleading. The Null type is there for compatibility with the Java virtual machine, and Java in particular.
We must consider that Scala:
is completely object oriented: every value is an object
is strongly typed: every value must have a type
needs to handle null references to access, for example, Java libraries and code
thus it becomes necessary to define a type for the null value, which is the Null trait, and has null as its only instance.
There is nothing especially useful in the Null type unless you're the type-system or you're developing on the compiler. In particular I can't see any sensible reason to define a Null type parameter for a method, since you can't pass anything but null
Do you have usages of Unit / Null / Nothing as something else than a
return type?
Unit can be used like this:
def execute(code: => Unit):Unit = {
// do something before
code
// do something after
}
This allows you to pass in an arbitrary block of code to be executed.
Null might be used as a bottom type for any value that is nullable. An example is this:
implicit def zeroNull[B >: Null] =
new Zero[B] { def apply = null }
Nothing is used in the definition of None
object None extends Option[Nothing]
This allows you to assign a None to any type of Option because Nothing 'extends' everything.
val x:Option[String] = None
if you use Nothing, there is no things to do (include print console)
if you do something, use output type Unit
object Run extends App {
//def sayHello(): Nothing = println("hello?")
def sayHello(): Unit = println("hello?")
sayHello()
}
... then how to use Nothing?
trait Option[E]
case class Some[E](value: E) extends Option[E]
case object None extends Option[Nothing]
I've never actually used the Null type, but you use Unit, where you would on java use void. Nothing is a special type, because as Nathan already mentioned, there can be no instance of Nothing. Nothing is a so called bottom-type, which means, that it is a sub-type of any other type. This (and the contravariant type parameter) is why you can prepend any value to Nil - which is a List[Nothing] - and the list will then be of this elements type. None also if of type Option[Nothing]. Every attempt to access the values inside such a container will throw an exception, because that it the only valid way to return from a method of type Nothing.
Nothing is often used implicitly. In the code below,
val b: Boolean =
if (1 > 2) false
else throw new RuntimeException("error")
the else clause is of type Nothing, which is a subclass of Boolean (as well as any other AnyVal). Thus, the whole assignment is valid to the compiler, although the else clause does not really return anything.
In terms of category theory Nothing is an initial object and Unit is a terminal object.
https://en.wikipedia.org/wiki/Initial_and_terminal_objects
Initial objects are also called coterminal or universal, and terminal objects are also called final.
If an object is both initial and terminal, it is called a zero object or null object.
Here's an example of Nothing from scala.predef:
def ??? : Nothing = throw new NotImplementedError
In case you're unfamiliar (and search engines can't search on it) ??? is Scala's placeholder function for anything that hasn't been implemented yet. Just like Kotlin's TODO.
You can use the same trick when creating mock objects: override unused methods with a custom notUsed method. The advantage of not using ??? is that you won't get compile warnings for things you never intend to implement.

Scala: invoking superclass constructor

I am experiencing a weird behavior by Scala handling of superclass constructors.
I have a really simple class defined in the following way
package server
class Content(identifier:String,content:String){
def getIdentifier() : String = {identifier}
def getContent() : String = {content}
}
and a simple subclass
package server
class SubContent(identifier:String, content:String) extends Content(identifier, content+"XXX")){
override def getContent():String = {
println(content)
super.getContent
}
}
What's really strange is that in the subclass there are duplicates of the superclass attributes, so if i create a new object
var c = new SubContent("x","x")
the execution of
c.getContent
first prints out "x" (The valued provided to the subclass constructor), but returns "xXXX" (The value provided to the superclass constructor).
Is there any way to avoid this behavior? Basically what I'd like to have is that the subclass does not create its own attributes but rather just passes the parameters to the superclass.
It's doing exactly what you told it to do. You augmented the 2nd constructor parameter when passing it on to the superclass constructor and then you used the superclass' getContent to provide the value returned from the subclass' getContent.
The thing you need to be aware of is that constructor parameters (those not tied to properties because they're part of a case class or because they were declared with the val keyword) are in scope throughout the class body. The class' constructor is that part of its body that is outside any method. So references to constructor parameters in method bodies forces the constructor parameter to be stored in a field so it can have the necessary extent. Note that your println call in getContent is causing such a hidden constructor parameter field in this case.
Replying to comment "Is there an alternative way to define it in order to avoid this? Or at least, if I never refer to the parameters of the subclass constructors their fields will be allocated (Wasting memory)?":
If the only references to plain constructor parameters (*) is in the constructor proper (i.e., outside any method body, and val and var initializers don't qualify as method bodies) then no invisible field will be created to hold the constructor parameter.
However, If there's more you're trying to "avoid" than these invisible fields, I don't understand what you're asking.
(*) By "plain constructor parameters" I mean those not part of a case class and not bearing the val keyword.