Imagine I had the following class structure:
class Parent {
public void method() {
// Some calculations
}
}
class Child extends Parent {
#Override
public void method() {
super.method();
// Some additional logic
}
}
I am spock-testing the Child.method and want to verify if the Parent.method is called from the Child.method. I did some research and i haven't found any satisfying solution to solve my problem.
How can I verify in a Spock test that in the call of Child.method the superclass method (Parent.method) was called as well?
Known solution: In Child move the super.method() to a separate, package-private method.
I want to know whether there is a better solution.
tim_yates commented:
Why do you want to test this? Can't you tell as the super class calculations were performed?
I completely agree. I would not test this because as #Override implies, the contract is an override, delegation to the super class method is optional. Why would you force your users to call the super class method? But as Tim said, you can test for the side effects which are important to you. Here is a little example with one side effect being a field assignment and another being something written to System.out (maybe silly, but just in order to show something non-obvious with a mock):
package de.scrum_master.stackoverflow.q60167623;
public class Parent {
protected String name;
public void method() {
// Some calculations
System.out.println("parent method");
name = "John Doe";
}
}
package de.scrum_master.stackoverflow.q60167623;
class Child extends Parent {
#Override
public void method() {
super.method();
// Some additional logic
System.out.println("child method");
}
public static void main(String[] args) {
new Child().method();
}
}
package de.scrum_master.stackoverflow.q60167623
import spock.lang.Specification
class ChildTest extends Specification {
static final PrintStream originalSysOut = System.out
PrintStream mockSysOut = Mock()
def setup() {
System.out = mockSysOut
}
def cleanup() {
System.out = originalSysOut
}
def test() {
given:
def child = new Child()
when:
child.method()
then:
1 * mockSysOut.println({ it.contains("parent") })
child.name == "John Doe"
}
}
Update: What you want to do simply is not possible technically, and for a reason: It would break encapsulation, see here, here, indirectly also here. The method is overridden, the word says it all. Test for the (side) effect or the result of a method, not for its interaction (that it is actually called). Spock's interaction testing capabilities are over-used even though the Spock manual warns about over-specification in some places. It just makes your tests brittle. Interaction testing is okay for design patterns like publish/subscribe (Observer pattern) where it makes sense to test the interactions between objects as such.
If you need to enforce that some functionality in Parent is called, you should enforce it via design not tests.
abstract class Parent {
public final void method() {
// Some calculations
additionalLogic();
}
protected abstract void additionalLogic();
}
class Child extends Parent {
#Override
protected void additionalLogic() {
super.method();
// Some additional logic
}
}
You could of course not make it abstract and just add a no-op implementation for additionalLogic() instead.
tim_yates and kriegaex are the big beasts in the jungle when it comes to good and bad Spock, or TDD-style testing generally ... they have more than once (rightly) picked apart my questions in the way they do here, basically on the basis of testing the code rather than the implementation.
Sometimes it's difficult though. Maybe there can be cases in which you would want to test for the calling of super.doSomething(). I am just putting together, using TDD, having already done a "spike", in which I rushed ahead without testing, an editor for a TreeTableView. The "spike" can be seen here. In a constructive comment to my answer, kleopatra advised me to check (i.e. put an if in the app code) to make sure that super.startEdit() had indeed started the editing of the cell before going further, so in this case it is not sufficient to test the "side-effect" of super.startEdit() as being that isEditing() now returns true. You genuinely need to know that your class's startEdit() actually does nothing more nor less than call super.startEdit().
However, I don't believe it can be done, and tim_yates or kriegaex would almost certainly have said how you could do that if it were possible.
My suggested TDD solution would therefore be something like this:
def 'super start edit should be called if cell is not empty'(){
given:
// NB has to be GroovySpy because isEmpty() is final
DueDateEditor editor = GroovySpy( DueDateEditor ){
isEmpty() >> false
}
when:
editor.startEdit()
then:
1 * editor.callSuperStartEdit()
}
class DueDateEditor extends TreeTableCell {
#Override
void startEdit(){
if( ! isEmpty() ) {
// this is the line you have to add to make the test pass
callSuperStartEdit()
}
}
def callSuperStartEdit(){
super.startEdit()
}
}
I think you have to "spawn" an artificial single-purpose method since there is, precisely, no side effect at all!
PS I will in fact parameterise this test so that it returns true to isEmpty() in the second call, and require the method NOT to be called in that case.
I´ve never used the Spock framework, but i think you can check the type of the instance in the Parent.method with instance of operator or reflection.
Related
I have a method which adds Objects to an static list like this:
#PostConstruct
protected void registerToTransactionList() {
TransactionValidator.registerTransactionList(this);
}
registerTransactionList method just adds "this" to the static list, this method is in BalanceTransactionValidator class which extends TransactionValidator (owner of static list),the problem is all subclasses of BalanceTransactionValidator class are added to static list either,and if I override registerToTransactionList method in them like this:
#Override
#PostConstruct
protected void registerToTransactionList() {
}
It doesn't add subclasses but doesn't add BalanceTransactionValidator either. Can anybody help me on this? Please notice sublasses are overriding this method by default.
make the method private to block the visibility
private void registerToTransactionList() {
}
or make the method final to block it from been override
protected final void registerToTransactionList() {
}
There are two ways of achieving that:
Keep your method as it is; but then you have to actively check for the type of your objects before externally calling that method
Change your whole logic and make that method private
It won't help to make the method final as suggested in one of the comments - your problem is not that subclasses are overwriting that method; in essence, you have a design problem: you wish that subclasses should not invoke that method at all.
So, the only real option that makes sense here is "2.". You see, by having public method on a class that you want to be extended you are implicitly saying: it is perfectly fine to call that method; on any object that is instance of the base class (or child class!).
And in your case, that is not true: you actually do not want that the code behind this method runs for child classes. Then you shouldn't put that method in the list of public/protected methods of your base class!
Finally: you might want to step back and do some reading about good OO design. Class hierarchies do not fall from the sky: you willfully design them for a certain purpose. In other words: there is more to inheritance than just putting some "A extends B" on your class declaration. You have to understand each and every method on your B class; and how your child classes should deal with them!
EDIT: after some more thinking, I guess you are doing things "the wrong way", like:
class BaseClass {
public final void doRegistration() {
BaseClass toRegister = getObjectForRegistration();
if (toRegister != null) { ... register toRegister ...
}
protected BaseClass getObjectForRegistration() {
return null;
}
With that code, you could then put
protected BaseClass getObjectForRegistration() {
if (this instanceof ClassThatShouldBeRegistered) {
return this;
}
return null;
}
into that one class that wants to be registered. Probably there could be even nicer ways of doing so; but after some thinking I don't see how we could avoid the instanceof. But the above code should work; and it only requires specific code only in your base class and in that one class that wants to register something.
I'll show my problem using this example:
I have a class with a method foo. That class has a subclass which overrides this method.
Subclass' method calls superclass' method. Can I verify that?
I don't want to test what foo in superclass does. I just need to verify that it was called.
I know that refactoring could help (favour composition over inheritance, etc) but I am unable to do that.
Is there any way to achieve what I need?
Below is simple example of what I've tried
package tmp;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.times;
public class Example {
#Test
public void test() {
// given
ChildClass childClass = new ChildClass();
ChildClass spyChildClass = Mockito.spy(childClass);
// when
spyChildClass.foo(100);
// then
Mockito.verify((BaseClass) spyChildClass, times(1)).foo(101);
}
}
abstract class BaseClass {
public void foo(int n) {
System.out.printf("BaseClass.foo(%d)%n", n);
}
}
class ChildClass extends BaseClass {
#Override
public void foo(int n) {
System.out.printf("ChildClass.foo(%d)%n", n);
super.foo(n + 1);
}
}
And this is the result:
ChildClass.foo(100)
BaseClass.foo(101)
Argument(s) are different! Wanted:
childClass.foo(101);
-> at tmp.Example.test(Example.java:19)
Actual invocation has different arguments:
childClass.foo(100);
-> at tmp.Example.test(Example.java:16)
Expected :childClass.foo(101);
Actual :childClass.foo(100);
<Click to see difference>
Obviously it's not what I wanted to see.
I can't modify BaseClass. I don't want to test BaseClass (I am not responsible for it). I don't even neet to know what exactly it does. I just need to verify that its method was called. Wnything else is not my problem. Its the problem of people who maintain BaseClass.
Test the behaviour of the class, not it's implementation.
Write the test such that the method is called and is expected to do something. Next check the object now represents what you now expect it to represent.
If BaseClass.foo is expected to increment some counter by 100, yet Subclass.foo increments some counter by 50 then calls the superclass, verify that the counter is now 150 and not just 50.
Don't peek the how - they may change over time. Do test the behaviour. The method foo may do other things besides increase counters - check the state of the object not what it did.
Possible solution: Make foo final, and decree that subclasses need to override some other method, the implementation of foo, instead of the actual foo.
abstract class BaseClass {
private boolean myFooCalled;
public final void foo(int n) {
myFooCalled = false;
fooImpl(int n);
if (!myFooCalled) { ... }
}
public void fooImpl(int n) {
myFooCalled = true;
System.out.printf("BaseClass.foo(%d)%n", n);
}
}
Notes: This is off the top of my head, so (1) I haven't tested it, (2) I'm not sure if this is what you really want, (3) I'm not sure whether your design ought to be improved. This is a general answer about "how you could make sure an overriding method calls the superclass method", not an answer tailored to your purposes.
I hesitate to give this answer because everyone here (including the OP) knows you can do this... but to answer the OP's question you can do this:
Instead of having
#Override
public void reset() throws IOException{
// ...
super.reset();
}
do this:
#Override
public void reset() throws IOException{
// ...
callSuperReset();
}
void callSuperReset() throws IOException {
super.reset();
}
... and verify that callSuperReset was indeed called...
I am a mocking newb (no doubt it shows), and I thought for a long time the command was simply "Thou shalt not create methods just to suit your tests".
But in a previous question of mine, davidxxx in his answer says
In fact I would say rather : "thou shalt not create methods to suit
your tests and that open the API of the application in an undesirable
way"
Given that this method callSuperReset is package-private, is there any problem in principle with it? (other than its total inelegance)
Yes, such a test can be written. And there is nothing wrong with wanting to do it, provided what you are testing is the contract of an API, not its implementation.
Here is a test for the contrived example in the question, using the JMockit mocking API:
#Test
public void subclassShouldObeyContractOfBaseClass(
#Mocked final BaseClass anyBaseInstance)
{
new ChildClass().foo(123);
new Verifications() {{ anyBaseInstance.foo(anyInt); }};
}
If necessary (as dictated by the contract of BaseClass#foo(int)), the test could also verify the argument value passed to the base method as being n + 1 (or whatever).
I ran into an interesting problem yesterday and while the fix was quite simple, I'm still a bit fuzzy on the "why" of it.
I have a class that has a private member variable that is assigned when it is instantiated, however if it is used in an abstract function that is called by the super class's constructor, the variable does not have a value. The solution to the problem was quite simple, I simply had to declare the variable as static and it was assigned correctly. Some code to illustrate the problem:
class Foo extends BaseClass
{
private final String bar = "fooBar!";
public Foo()
{
super();
}
#Override
public void initialize()
{
System.out.println(bar);
}
}
And the base class:
abstract class BaseClass
{
public BaseClass()
{
initialize();
}
public abstract void initialize();
}
In this example, when we call new Foo(); it will output (null) instead of the expected fooBar!
Since we're instantiated an object of type Foo, should its members not be allocated and assigned prior to calling its (and consequently its super class's) constructor? Is this specified somewhere in the Java language or is it JVM specific?
Thanks for any insight!
The assignment of bar = "fooBar!"; is inlined into the constructor during compile time.
The superclass constructor runs before the subclass constructor, hence it would only be natural that the statement is executed afterwards.
Generally though, it's bad practice to call overridable methods from a constructor.
It is as defined by the Java Language Specification. Changing it to static will almost never be and acceptable solution in real world situation.
See JLS 4.12.5 Initial Values of Variablesand JLS 8.3.2 Initialization of Fields
Overall, it is bad practice to call a non-final method from a constructor. the reason being that it could (and if the method is abstract then definitely does) call method in the class that has not yet been initialized: When new Foo() is executed, the BaseClass initializer (constructor) gets called before the Foo constructor, so Foo.initialize is essentially working on an Object that has not been fully constructed yet.
There's just one thing I would like to add to the accepted answer, because I don't entirely agree with his conclusion.
We've all done this.
class Engine {
public Engine() {
init();
}
void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
...
}
Now the question is, which access modifier should we add to our init() function. Should it be private or protected.
make it private <-- keeps subclasses out
make it protected <-- allows subclasses in
Before you make a choice
Now first of all, you should realize that (almost) all code in the Engine class can be replaced by a subclass.
code in a public function, can easily be overridden
code in a protected function, can easily be overridden
code in a private function, can be replaced by overriding all methods that call it.
Well, there is just one exception:
you can never modify the code of a constructor
you can never avoid a private method being called from the constructor of a super class.
(and of course, you cannot replace a final method)
Protected init() - the wrong way
Let's say the init() method is protected there is indeed a pitfall. It is tempting to override it to add features as follows. That would indeed be a mistake.
class SubEngine extends Engine {
int screws = 5;
void init() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this won't print 5, but it will print 0.
System.out.println("tightening " + screws + " screws");
}
}
Protected init() - the right way
So, basically, you should just disable the parents code and postpone execution to your own constructor instead.
class SubEngine extends Engine {
int screws = 5;
public SubEngine() {
initSubEngine();
}
void init() {
// disable parent code
}
void initSubEngine() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this will print 5 as expected
System.out.println("tightening " + screws + " screws");
}
}
Private init() - you may need a phonecall
Now, what if the init() method is private ?
Like mentioned above, there is no way to disable the code of a parent constructor. And if init() is private you simply cannot disable it.
You'll end up copying the entire Engine class, perhaps just to add 1 line of code.
And that may not be the end of it. Even after copying your class, your copied object won't be an Engine meaning that you won't be able to use your EngineUtil#inspectEngine(Engine engine) function.
Perhaps somebody knew this in advance and made an IEngine interface. Then you can get away with it.
In practice it means you'll have to take your phone, and call to that other department that made the Engine class, and ask them to change their code a little to take away some restrictions.
Intelligent design
There is another way. Constructors are for setting variables. They shouldn't activate anything. Everytime you see a class creating a new Thread from their constructor (or through a private method) that should be a red flag.
class Engine {
public Engine() {
}
public void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
// and you probably also want one of these
public void shutdown() { ... }
...
}
Intention
Of course, your intention may very well be not to open up your code. Perhaps you really don't want to allow others to extend your classes. There certainly can be cases where you want to lock people out.
Be aware that it will also make it harder to write tests for your code.
Anyway that's a different scenario.
I have a method in my static state machine that is only used once when my application is first fired up. The method needs to be public, but I still want it hidden. Is there a way to use an annotation or something that will hide the method from the rest of the project?
You cannot make a public method hidden (unless you can declare it private). You can however put in a subclass and only let the users of the object know the type of the superclass, that is:
class A {
//Externally visible members
}
class B extends A {
//Secret public members
}
Then you instantiate the class B, but only let the type A be known to others...
Once you declare public method it becomes part of your class's contract. You can't hide it because all class users will expect this method to be available.
You could use package level instead of public. That way it can only be called by your application.
If a method is public, it can't be hidden. What you may really be looking for is just a way to restrict access to calling a method. There are other ways to achieve a similar effect.
If there are some things that your state machine does that are "only used once when my application is first fired up" it sounds a lot like those are things that could happen in the constructor. Although it depends on how complex those tasks are, you may not want to do that at construction time.
Since you said your state machine is static, is it also a Singleton? You could maybe use the Singleton Pattern.
public class SimpleStateMachine {
private static SimpleStateMachine instance = new SimpleStateMachine();
private SimpleStateMachine() {
super();
System.out.println("Welcome to the machine"); // prints 1st
}
public static SimpleStateMachine getInstance() {
return instance;
}
public void doUsefulThings() {
System.out.println("Doing useful things"); // prints 3rd
}
}
Here's some code for a client of this Singleton:
public class MachineCaller {
static SimpleStateMachine machine = SimpleStateMachine.getInstance();
public static void main(String... args) {
System.out.println("Start at the very beginning"); // prints 2nd
machine.doUsefulThings();
}
}
Note that the SimpleStateMachine instance isn't built until the first time your class is accessed. Because it's declared as static in the MachineCaller client, that counts as a "first access" and creates the instance. Keep this tidbit in mind if you definitely want your state machine to perform some of those initialization tasks at the time your application starts up.
So, if you don't want to turn your state machine class into a true singleton... you can use a static initialization block do your one-time tasks the first time the class is accessed. That would look something like this:
public class SimpleStateMachine {
static {
System.out.println("First time tasks #1");
System.out.println("First time tasks #2");
}
public SimpleStateMachine() {
super();
System.out.println("Welcome to the machine");
}
public void doUsefulThings() {
System.out.println("Doing useful things");
}
}
While we're at it, since you mentioned that it's a state machine... the Head First Design Patterns book does a nice, easily understandable treatment of the State Pattern. I recommend reading it if you haven't already.
The idiomatic approach to doing this is to use interfaces to limit the visibility of your methods.
For example, say you have the following class:
public class MyClass {
public void method1() {
// ...
}
public void method2() {
// ...
}
}
If you want to limit some parts of the project to only see method1(), then what you do is describe it in an interface, and have the class implement that interface:
public interface Method1Interface {
public void method1();
}
...
public class MyClass implements Method1Interface {
public void method1() {
// ...
}
public void method2() {
// ...
}
}
Then, you can limit the visibility of the methods by choosing to pass the class around either as a MyClass reference, or as a Method1Interface reference:
public class OtherClass {
public void otherMethod1(MyClass obj) {
// can access both obj.method1() and obj.method2()
}
public void otherMethod2(Method1Interface obj) {
// can only access obj.method1(), obj.method2() is hidden.
}
}
A bonus of this approach is that it can also be easily extended. Say, for example, you now also want to independently control access to method2(). All you need do is create a new Method2Interface along the same lines as Method1Interface, and have MyClass implement it. Then, you can control access to method2() in exactly the same manner as method1().
This is a similar approach to that advocated in #MathiasSchwarz's answer, but is much more flexible:
The independent access control described in the preceding paragraph isn't possible with Mathias' technique, due to Java not supporting multiple inheritance.
Not requiring an inheritance relationship also allows more flexibility in designing the class hierarchy.
The only change required to the original class is to add implements Method1Interface, which means that it is a very low-impact refactor since existing users of MyClass don't have to be changed at all (at least, until the choice is made to change them to use Method1Interface).
An alternative solution: You can make it private and create a invokeHiddenMethod(String methodName, Object ... args) method using reflection.
You said that your public method is used only once when the application is started up.
Perhaps you could leave the method public, but make it do nothing after the first call?
There is a (non-)keyword level package level visibility. Instead of public, protected, or private, you use nothing.
This would make the method or class visible to the class and others in the package, but would give you a certain modicum of privacy. You may want to look at What is the use of package level protection in java?.
Hmm... You want a private method, but want to access it outside?
Try do this with reflection.
http://download.oracle.com/javase/tutorial/reflect/index.html
I have seen many Java programmers do something like this:
public static void main(String args[]) {
new MyClass();
}
So basically they create just one object of the class. If there is a method which should run only once, I guess this approach can achieve that. Your method will be called from inside the constructor. But since I don't know how your app works, what are the constraints, so it is just a thought.
public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
System.out.println ("Parameters for subclass method were: ....");
}
}
public class Owner extends Master {
public void printSomething () {
System.out.println ("This printed from Owner");
}
public int returnSomeCals ()
{
return 5+5;
}
}
Without messing with methods of subclass...is it possible to execute printForAllMethodsInSubClass() before the method of a subclass gets executed?
update:
Using AspectJ/Ruby/Python...etc
Would it also be possible to print the parameters? Above code formatted below:
public abstract class Master
{
public void printForAllMethodsInSubClass()
{
System.out.println ("Printing before subclass method executes");
}
}
public class Owner extends Master {
public void printSomething (String something) {
System.out.println (something + " printed from Owner");
}
public int returnSomeCals (int x, int y)
{
return x+y;
}
}
AspectJ can provide this functionality for you, but it's a separate compilation step and some extra libraries involved.
public aspect ServerLogger {
pointcut printSomething ();
before(): printSomething()
{
(Master)(thisJoinPointStaticPart.getTarget()).printForAlMethodsInSubClass();
}
}
The Eclipse Project provides a great implementation of AspectJ that integrates nicely with Eclipse and Maven. There's a boatload of great documentation available for it, and a lot of really good material for it here on StackOverflow.
[update]
To access parameter info, you can use the
thisJoinPoint.getSignature();
method to access information about the function being called if the returned Object is an instance of MethodSignature, you can use Signature.getParameterNames() to access the parameters to the function being called. You'd have to use a bit of reflection to actually get at the values, I think - AspectJ doesn't seem to handle this for you. I'd have to actually do some experimentation to get some working code for you.
To answer the "any other programming language": It's easily possible in Ruby:
class Master
REDEFINED = []
def printForAllMethodsInSubClass
puts 'Printing before subclass method executes'
end
def self.method_added(meth)
if self < Master and not Master::REDEFINED.include? meth
new_name = "MASTER_OVERRIDE_#{meth}".intern
Master::REDEFINED.push meth, new_name
alias_method new_name, meth
define_method(meth) {|*args| printForAllMethodsInSubClass; send(new_name, *args)}
end
end
end
You could also make a proxy declaration method to use in subclasses:
class Master
def printForAllMethodsInSubClass
Printing before subclass method executes
end
def self.master_method(name)
define_method(name) {|*args| printForAllMethodsInSubClass; yield *args}
end
end
class Owner
master_method(:print_something) do
puts "This was printed from Owner"
end
end
(This approach would also translate very naturally to Python decorators.)
This is possible in aspect-oriented programming languages, such as AspectJ.
In Python you can accomplish this using meta classes, here's a small example. You can probably make it more elegantly but it is just to make the point
import types
class PrintMetaClass(type):
def __init__(cls, name, bases, attrs):
# for every member in the class
override = {}
for attr in attrs:
member = attrs[attr]
# if it's a function
if type(member) == types.FunctionType:
# we wrap it
def wrapped(*args, **kwargs):
print 'before any method'
return member(*args, **kwargs)
override[attr] = wrapped
super(PrintMetaClass, cls).__init__(name, bases, attrs)
for attr in override:
setattr(cls, attr, override[attr])
class Foo:
__metaclass__ = PrintMetaClass
def do_something(self):
print 2
class Bar(Foo):
def do_something_else(self):
print 3
In this example, the PrintMetaClass gets in the way of the creation of the Foo class and any of its subclasses redefining every method to be a wrapper of the original and printing a given message at the beginning. The Bar class receives this aspect-like behavior simply by inheriting from Foo which defines its __metaclass__ to be PrintMetaClass.
Metaclasess in OOP:
http://en.wikipedia.org/wiki/Metaclass
Metaclasses in python:
http://www.python.org/doc/essays/metaclasses/
http://www.ibm.com/developerworks/linux/library/l-pymeta.html
Besides aspect oriented programming have a look at Template Method Pattern, http://en.wikipedia.org/wiki/Template_method_pattern.
In short: the parent class have an abstract method, which subclasses have to implement, this abstract method is called by a method in the parent class where put your printouts or whatever necessary statements.