Mocking void functions using EasyMock with dynamic behaviour - testing

I need to mock a void function with EasyMock such that the first call returns an Exception, while the next succeeds.
For example:
this.myObject.move((String) EasyMock.anyObject());
EasyMock.expectLastCall().once().andThrow(new RetryableDependencyException());
EasyMock.expectLastCall().once();
But this is not working.

That's not going to work as the second expectLastCall() cannot find any call.
Have you tried this:
this.myObject.move((String) EasyMock.anyObject());
EasyMock.expectLastCall().once().andThrow(new RetryableDependencyException());
this.myObject.move((String) EasyMock.anyObject());
EasyMock.expectLastCall().once();
I know it's a bit verbose but it should get you sorted :)

The shortest is
myObject.move(anyString());
expectLastCall().andThrow(new RetryableDependencyException()).asStub();
which assumes that is doesn't matter if the method is called more than once after the exception. If it matters, it will be
myObject.move(anyString());
expectLastCall().andThrow(new RetryableDependencyException());
myObject.move(anyString());
Interesting facts:
You can chain andReturn
I highly suggest static imports to get a cleaner code
anyString is used to prevent the cast in String
once() is not required as it is the default
expectLastCall isn't required, calling the void method is enough to record a call without any side effect (like a throw)

Related

How to make a class that inherits the same methods as IO::Path?

I want to build a class in Raku. Here's what I have so far:
unit class Vimwiki::File;
has Str:D $.path is required where *.IO.e;
method size {
return $.file.IO.s;
}
I'd like to get rid of the size method by simply making my class inherit the methods from IO::Path but I'm at a bit of a loss for how to accomplish this. Trying is IO::Path throws errors when I try to create a new object:
$vwf = Vimwiki::File.new(path => 't/test_file.md');
Must specify a non-empty string as a path
in block <unit> at t/01-basic.rakutest line 24
Must specify a non-empty string as a path
I always try a person's code when looking at someone's SO. Yours didn't work. (No declaration of $vwf.) That instantly alerts me that someone hasn't applied Minimal Reproducible Example principles.
So I did and less than 60 seconds later:
IO::Path.new
Yields the same error.
Why?
The doc for IO::Path.new shows its signature:
multi method new(Str:D $path, ...
So, IO::Path's new method expects a positional argument that's a Str. You (and my MRE) haven't passed a positional argument that's a Str. Thus the error message.
Of course, you've declared your own attribute $path, and have passed a named argument to set it, and that's unfortunately confused you because of the coincidence with the name path, but that's the fun of programming.
What next, take #1
Having a path attribute that duplicates IO::Path's strikes me as likely to lead to unnecessary complexity and/or bugs. So I think I'd nix that.
If all you're trying to do is wrap an additional check around the filename, then you could just write:
unit class Vimwiki::File is IO::Path;
method new ($path, |) { $path.IO.e ?? (callsame) !! die 'nope' }
callsame redispatches the ongoing routine call (the new method call), with the exact same arguments, to the next best fitting candidate(s) that would have been chosen if your new one containing the callsame hadn't been called. In this case, the next candidate(s) will be the existing new method(s) of IO::Path.
That seems fine to get started. Then you can add other attributes and methods as you see fit...
What next, take #2
...except for the IO::Path bug you filed, which means you can't initialize attributes in the normal way because IO::Path breaks the standard object construction protocol! :(
Liz shows one way to workaround this bug.
In an earlier version of this answer, I had not only showed but recommended another approach, namely delegation via handles instead of ordinary inheritance. I have since concluded that that was over-complicating things, and so removed it from this answer. And then I read your issue!
So I guess the delegation approach might still be appropriate as a workaround for a bug. So if later readers want to see it in action, follow #sdondley's link to their code. But I'm leaving it out of this (hopefully final! famous last words...) version of this answer in the hope that by the time you (later reader) read this, you just need to do something really simple like take #1.

Mockito - Is it possible to deep mock a void method call to do nothing?

I wanted to know if it is possible to "deep mock" a void method call without breaking out the call chain, using Mockito.
This is an example for the original call I want to mock:
obj.getSomething().add(3);
where "add"'s return type is void.
I tried:
doNothing().when(obj).getSomething().add(3)
and:
doNothing().when(obj.getSomething()).add(3) //wont work since "when" expects a mock.
I also failed using Mockito.when(...) since it does not work with void methods.
I do not want to break the call up since it will be very cumbersome for fluent API calls that are much longer.
Is there an official solution / workaround for this scenario?
Thanks :)
If the value returned by getSomething is not a mock, it won't work.
Return value of getSomething should be a mock and it will allow to assign mock behavior for that value.
Something someMock = mock(Something.class);
when(obj.getSomething()).thenReturn(someMock);
doNothing().when(someMock).add(3);

How can one invoke the non-extension `run` function (the one without scope / "object reference") in environments where there is an object scope?

Example:
data class T(val flag: Boolean) {
constructor(n: Int) : this(run {
// Some computation here...
<Boolean result>
})
}
In this example, the custom constructor needs to run some computation in order to determine which value to pass to the primary constructor, but the compiler does not accept the run, citing Cannot access 'run' before superclass constructor has been called, which, if I understand correctly, means instead of interpreting it as the non-extension run (the variant with no object reference in https://kotlinlang.org/docs/reference/scope-functions.html#function-selection), it construes it as a call to this.run (the variant with an object reference in the above table) - which is invalid as the object has not completely instantiated yet.
What can I do in order to let the compiler know I mean the run function which is not an extension method and doesn't take a scope?
Clarification: I am interested in an answer to the question as asked, not in a workaround.
I can think of several workarounds - ways to rewrite this code in a way that works as intended without calling run: extracting the code to a function; rewriting it as a (possibly highly nested) let expression; removing the run and invoking the lambda (with () after it) instead (funnily enough, IntelliJ IDEA tags that as Redundant lambda creation and suggests to Inline the body, which reinstates the non-compiling run). But the question is not how to rewrite this without using run - it's how to make run work in this context.
A good answer should do one of the following things:
Explain how to instruct the compiler to call a function rather than an extension method when a name is overloaded, in general; or
Explain how to do that specifically for run; or
Explain that (and ideally also why) it is not possible to do (ideally with supporting references); or
Explain what I got wrong, in case I got something wrong and the whole question is irrelevant (e.g. if my analysis is incorrect, and the problem is something other than the compiler construing the call to run as this.run).
If someone has a neat workaround not mentioned above they're welcome to post it in a comment - not as an answer.
In case it matters: I'm using multi-platform Kotlin 1.4.20.
Kotlin favors the receiver overload if it is in scope. The solution is to use the fully qualified name of the non-receiver function:
kotlin.run { //...
The specification is explained here.
Another option when the overloads are not in the same package is to use import renaming, but that won't work in this case since both run functions are in the same package.

OCMock and overriding stub value

mockModule = OCMPartialMock(module);
OCMStub([mockModule send:#"FOO"]).andReturn(YES);
OCMStub([mockModule send:#"FOO"]).andReturn(NO);
In this example I have a simple mock module, and I set some stubs to return YES/NO when sent a String, the problem that occurs is that if I set the same string twice it only returns the first value, and not the new value.
In this example about the problem is demonstrated like so I would expect a call such as:
BOOL answer = [module send:#"FOO"]
//answer should be NO, but is YES
How can I make it respond with the most recently set value?
You could use the expect methods, e.g.
mockModule = OCMPartialMock(module);
OCMExpect([mockModule send:#"FOO"]).andReturn(YES);
OCMStub([mockModule send:#"FOO"]).andReturn(NO);
That's not exactly what they are meant for, but it does make some sense. You're basically saying, I expect that send: will be called, and when that has actually happened, then I want the method to be stubbed.
Also, if it were possible to "pile up" the stubs, figuring out what went wrong would be quite difficult, e.g. if the first invocation of the stub doesn't happen, then the second invocation will get the value meant for the first.

What is the appropriate amount of error-checking?

public void PublicMethod(FooBar fooBar)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null");
// log the call [added: Thanks S.Lott]
_logger.Log("PublicMethod called with fooBar class " + fooBar.Classification);
int action = DetermineAction();
PrivateMethod(fooBar, action);
}
private void PrivateMethod(FooBar fooBar, int action)
{
if (fooBar == null)
throw new ArgumentNullException("fooBar", "fooBar cannot be null"); // Is this line superfluous?
/*
Do something
*/
}
Is it OK to skip this kind of error checking in private methods if the input is already checked on the public interface? Usually there's some sort of rule-of-thumb one can go by...
Edit:
Maybe ArgumentNullException isn't such a good example because the argument can be made that you should check at both levels but return different error messages.
I would say no.
While it certainly holds true that you in this case knows that it has already been checked for nullability, in two months time the youngest intern will come along and write
PublicMethod2 that also calls PrivateMethod, but lo and behold he forgot to check for null.
Since the public method doesn't really use foobar, I'm not sure why it's checking. The current private method cares, but it's the private method's responsibility to care. Indeed, the whole point of a private method is to delegate all the responsibilities to it.
A method checks the input it actually uses; it doesn't check stuff it's just passing through.
If a different subclass has the same public method, but some different private method implementation -- one that can tolerate nulls -- what now? You have a public method that now has wrong constraints for the new subclass.
You want to do as little as possible in the public method so that various private implementations are free to do the right thing. Don't "over-check" or "just-in-case" check. Delegate responsibility.
I'd error check everything you can, you never know when something might happen that you didn't think about. (and its better safe than sorry)
When using design by contract (http://en.wikipedia.org/wiki/Design_by_contract) it’s normally client’s (public method) responsibility to make correct invocation, i.e. pass on valid parameters. In this particular scenario it depends whether null belongs to a set of valid input values, therefore there are 3 options:
1) Null is valid value: throwing exceptions or errors would have meant breaking the contract, the server (private method) has to process the null and shouldn’t complain.
2) Null is invalid value and passed by code within your control: it is up to the server (private method) to decide how to react. Obviously, throwing an exception is more graceful way of handling the situation, but it has a cost of having to handle that exception somewhere else up the stack. Exceptions are not the best way to deal with violation of contract caused by programming blunders. You really should throw exceptions not when a contract is already violated but when it cannot be fulfilled because of environmental problems what cannot be controlled in software. Blunders are better handled by sticking an assertion into the beginning of the private method to check that the parameter is not null. This will keep the complexity of your code down, there is no cost of having to handle the exception up the stack and it will achieve the goal of highlighting broken contracts during testing.
3) Then there is defensive programming (http://en.wikipedia.org/wiki/Defensive_programming). When dealing with parameters passed by an external code outside your control the immediate layer of your code needs to run paranoid level of checks and return errors according to its communication contract with the external world. Then, going deeper into the code layers not exposed externally, it still makes more sense to stick to the programming by contract.
At least put a comment that PrivateMethod must have a non-null FooBar and that PublicMethod checks this.
You might want to also mark the "private" method as private or protected.
That depends if a null-value indicates an error for a method. Remember that methods could also be called messages to an object; they operate on the state of the object aswell. Parameters can specialize the kind of message sent.
If publicMethod() does not use a parameter and changes the state of the instance while privateMethod() uses the parameter, do not consider it an error in publicMethod, but do in privateMethod().
If publicMethod() does not change state, consider it an error.
You could see the latter case as providing an interface to the internal functioning of an object.
I'd consider the answer to be "yes, do the check again" because:-
The private member could be reused again in the future from a different path through the code, so program defensively against that situation.
If you perform unit tests on private methods
My view might change if I had a static analyser that could pick this up and not flag the potential use of a null reference in the private method.
In cases where PrivateMethod will be called frequently with input that has already been verified, and only rarely with user input, Then I would use the PublicMethod/PrivateMethod concept with no error checking on PrivateMethod (and with PublicMethod doing nothing other then checking the parameters and calling PrivateMethod)
I would also call the private method something like PublicMethod_impl (for "implementation") so it's clear that it's an internal use/ no checking method.
I maintain that this design leads to more robust application, as it forces you to think about what's checked when. Too often people who always check parameters fall into the trap of "I've checked something, therefore I've checked everything".
As an example of this, a former co-worker (programming in C) would, before using a pointer, always check to see if it was null. Generally, the pointers in his code were initialized as startup and never changed, so the chances of it being null were quite low. Moreover, the pointer has one correct value and 65535 possible wrong values, and he was only checking for one of those wrong values.