As per THIS post, There are two ways to mock the method doSomeStuff() to return a 1 :
when(bloMock.doSomeStuff()).thenReturn(1);
and
doReturn(1).when(bloMock).doSomeStuff();
The very important difference is that the first option will actually
call the doSomeStuff()- method while the second will not
So, my question is what is the point in having the first option which actually calls the actual method but returns 1 only. In which use case, we may want to something like that?
I dug a bit more than this, and the answer to why both syntaxes exist can be found in the old release notes, and a referenced mailing list discussion.
To start with, doReturn() was added in version 1.5 (26/07/2008), while when() was added in version 1.6 (21/10/2008). when() was implemented to replace the old stub() method and doReturn() to replace stubVoid(). Basically this is a design deicision by the creator of Mockito (cited from the mailing list 29/06/2008):
I never liked stubVoid() syntax but that was the best I could think
of. The stubbing syntax I'd implement now if I did mockito again:
//regular stubbing:
when(mock.getStuff()).thenReturn("foo");
when(mock.getStuff()).thenThrow(new RuntimeException());
//for void methods and some corner cases:
doReturn("foo").when(mock).getStuff();
doThrow(new RuntimeException()).when(mock).someMethod();
//for stubbing consecutively:
when(mock.getStuff()).thenReturn("foo").thenThrow(new RuntimeException());
doThrow(new RuntimeException()).thenReturn("foo").when(mock).someMethod();
I proposed this syntax couple of weeks ago but received only single
feedback saying that it's rather cosmetic (which is true...). Hence I
decided not to change the API.
And as already pointed out by Bewusstsein in the comments, when() provides type safety. If we have a method String doSomething() both below blocks will compile. The latter will however throw an exception during runtime.
Mockito.doReturn("String").when(mock).doSomething();
Mockito.doReturn(1).when(mock).doSomething();
So, to conclude, it was a design decision to introduce both ways of mocking. when() was imlemented as the prefered way of mocking, due to its type safety and its fluent reading. doReturn() was implemented to allow for mocking of void methods and other corner cases.
Related
What's the difference between doThrow() and thenThrow()?
Let's say, we want to mock an authentication service to validate the login credentials of a user. What's the difference between the following two lines if we were to mock an exception?
doThrow(new BadCredentialsException("Wrong username/password!")).when(authenticationService).login("user1", "pass1");
vs
when(authenticationService.login("user1", "pass1")).thenThrow(new BadCredentialsException("Wrong username/password!"));
Almost nothing: in simple cases they behave exactly the same. The when syntax reads more like a grammatical sentence in English.
Why "almost"? Note that the when style actually contains a call to authenticationService.login. That's the first expression evaluated in that line, so whatever behavior you have stubbed will happen during the call to when. Most of the time, there's no problem here: the method call has no stubbed behavior, so Mockito only returns a dummy value and the two calls are exactly equivalent. However, this might not be the case if either of the following are true:
you're overriding behavior you already stubbed, particularly to run an Answer or throw an Exception
you're working with a spy with a non-trivial implementation
In those cases, doThrow will call when(authenticationService) and deactivate all dangerous behavior, whereas when().thenThrow() will invoke the dangerous method and throw off your test.
(Of course, for void methods, you'll also need to use doThrow—the when syntax won't compile without a return value. There's no choice there.)
Thus, doThrow is always a little safer as a rule, but when().thenThrow() is slightly more readable and usually equivalent.
I have two different types, TypeA and TypeB, both of which are relatable in the sense that they describe the same concept but from different view points - though there exists a loose temporal relationship.
I want to create a utility method which tests to see if the two types I pass into the utility method are in fact related.
The objects are not directly equitable, but I thought that they might be Comparable (which they are), however when I look at the description of ICompareable, it suggest that this should be implemented to assist sorting of arrays.
Is there a better interface to use, or should I just create my own comparer routine which does not implement any interface. This is what I am going with for now, but I thought there might be a more pattern specific solution, hence the question.
I would go for an own solution, as neither IComparer nor IEquatable are matching your requirement.
Maybe just bool IsRelatedTo() instance method would be enough?
Background: I am programming a .NET compiler (very similar to C#) for a school project. One of the features I am currently trying to add is tailcall recursion within methods.
More info: In CIL, the "this" is passed into instance methods as if it were just another argument. So, accessing the first argument of a static method, you would emit ldarg.0, but accessing the first argument of an instance method, you would emit ldarg.1, and accessing "this" in an instance method you would emit ldarg.0. (Instance methods are even more similar to extension methods than I ever imagined.)
Question: Can you set "this" using starg.0 without any side effects?
Why this is in question: Whether or not a method is an instance method is set with the MethodBuilder, which is a bit of a black box. Although "this" seems just like any other argument, for all I know some JIT compilers keep track of "this" separately and change their behavior depending on this value. If there are side effects when you set "this" in an instance method, then how can I avoid them?
You may want to have a look at how F# implements tail-call.
You can extract this as a local variable. This way you will know that you can set it safely. (I hope I understand your question correctly)
I have an upcoming project in which a core requirement will be to mutate the way a method works at runtime. Note that I'm not talking about a higher level OO concept like "shadow one method with another", although the practical effect would be similar.
The key properties I'm after are:
I must be able to modify the method in such a way that I can add new expressions, remove existing expressions, or modify any of the expressions that take place in it.
After modifying the method, subsequent calls to that method would invoke the new sequence of operations. (Or, if the language binds methods rather than evaluating every single time, provide me a way to unbind/rebind the new method.)
Ideally, I would like to manipulate the atomic units of the language (e.g., "invoke method foo on object bar") and not the assembly directly (e.g. "pop these three parameters onto the stack"). In other words, I'd like to be able to have high confidence that the operations I construct are semantically meaningful in the language. But I'll take what I can get.
If you're not sure if a candidate language meets these criteria, here's a simple litmus test:
Can you write another method called clean which:
accepts a method m as input
returns another method m2 that performs the same operations as m
such that m2 is identical to m, but doesn't contain any calls to the print-to-standard-out method in your language (puts, System.Console.WriteLn, println, etc.)?
I'd like to do some preliminary research now and figure out what the strongest candidates are. Having a large, active community is as important to me as the practicality of implementing what I want to do. I am aware that there may be some unforged territory here, since manipulating bytecode directly is not typically an operation that needs to be exposed.
What are the choices available to me? If possible, can you provide a toy example in one or more of the languages that you recommend, or point me to a recent example?
Update: The reason I'm after this is that I'd like to write a program which is capable of modifying itself at runtime in response to new information. This modification goes beyond mere parameters or configurable data, but full-fledged, evolved changes in behavior. (No, I'm not writing a virus. ;) )
Well, you could always use .NET and the Expression libraries to build up expressions. That I think is really your best bet as you can build up representations of commands in memory and there is good library support for manipulating, traversing, etc.
Well, those languages with really strong macro support (in particular Lisps) could qualify.
But are you sure you actually need to go this deeply? I don't know what you're trying to do, but I suppose you could emulate it without actually getting too deeply into metaprogramming. Say, instead of using a method and manipulating it, use a collection of functions (with some way of sharing state, e.g. an object holding state passed to each).
I would say Groovy can do this.
For example
class Foo {
void bar() {
println "foobar"
}
}
Foo.metaClass.bar = {->
prinltn "barfoo"
}
Or a specific instance of foo without effecting other instances
fooInstance.metaClass.bar = {->
println "instance barfoo"
}
Using this approach I can modify, remove or add expression from the method and Subsequent calls will use the new method. You can do quite a lot with the Groovy metaClass.
In java, many professional framework do so using the open source ASM framework.
Here is a list of all famous java apps and libs including ASM.
A few years ago BCEL was also very much used.
There are languages/environments that allows a real runtime modification - for example, Common Lisp, Smalltalk, Forth. Use one of them if you really know what you're doing. Otherwise you can simply employ an interpreter pattern for an evolving part of your code, it is possible (and trivial) with any OO or functional language.
I recently took in a small MCF C++ application, which is obviously in a working state. To get started I'm running PC-Lint over the code, and lint is complaining that CStringT's are being passed to Format. Opinion on the internet seems to be divided. Some say that CSting is designed to handle this use case without error, but others (and an MSDN article) say that it should always be cast when passed to a variable argument function. Can Stackoverflow come to any consensus on the issue?
CString has been carefully designed to be passed as part of a variable argument list, so it is safe to use it that way. And you can be fairly sure that Microsoft will take care not to break this particular behavior. So I'd say you are safe to continue using it that way, if you want to.
That said, personally I'd prefer the cast. It is not common behavior that string classes behave that way (e.g. std::string does not) and for mental consistency it may be better to just do it the "safe" way.
P.S.: See this thread for implementation details and further notes on how to cast.