Mockito InvalidUseOfMatchersException despite using only matchers (and hint seems to mention wrong number of parameters) - exception

I ran into a well-known InvalidUseOfMatchersException even though I was using all matchers.
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 2 recorded:
-> at com.spotify.adaccountservice.utils.RoleUtilsTest.test_addOrRemoveRole_AddUserToAdAccount(RoleUtilsTest.java:179)
-> at com.spotify.adaccountservice.utils.RoleUtilsTest.test_addOrRemoveRole_AddUserToAdAccount(RoleUtilsTest.java:180)
I know we don't like screenshots of code here, but I want to convince that it's indeed happening at these line numbers:
And here's the actual method:
So it was kind of strange. Why is it expecting 3 matchers, when the method has 4 parameters? And why is it only "recording" 2 of them, when I'm using eq() for all of them?
Self-answering, as the error misdirected me. (Or, maybe someone can explain why it was actually accurate.)

Turns out it was because one of the variables in my 3rd argument, portcullisUtils, was a mock object that I forgot to stub for getAdAccountRoleId(...).
I suppose the program can't really tell that of course I didn't mean to match against such an abstraction, and did something weird.
Will accept whoever's answer can explain why these particular error messages.

Related

Why is my %h is List = 1,2; a valid assignment?

While finalizing my upcoming Raku Advent Calendar post on sigils, I decided to double-check my understanding of the type constraints that sigils create. The docs describe sigil type constraints with the table
below:
Based on this table (and my general understanding of how sigils and containers work), I strongly expected this code
my %percent-sigil is List = 1,2;
my #at-sigil is Map = :k<v>;
to throw an error.
Specifically, I expected that is List would attempt to bind the %-sigiled variable to a List, and that this would throw an X::TypeCheck::Binding error – the same error that my %h := 1,2 throws.
But it didn't error. The first line created a List that seemed perfectly ordinary in every way, other than the sigil on its variable. And the second created a seemingly normal Map. Neither of them secretly had Scalar intermediaries, at least as far as I could tell with VAR and similar introspection.
I took a very quick look at the World.nqp source code, and it seems at least plausible that discarding the % type constraint with is List is intended behavior.
So, is this behavior correct/intended? If so, why? And how does that fit in with the type constraints and other guarantees that sigils typically provide?
(I have to admit, seeing an %-sigiled variable that doesn't support Associative indexing kind of shocked me…)
I think this is a grey area, somewhere between DIHWIDT (Docter, It Hurts When I Do This) and an oversight in implementation.
Thing is, you can create your own class and use that in the is trait. Basically, that overrides the type with which the object will be created from the default Hash (for %) and Array (for # sigils). As long as you provide the interface methods, it (currently) works. For example:
class Foo {
method AT-KEY($) { 42 }
}
my %h is Foo;
say %h<a>; # 42
However, if you want to pass such an object as an argument to a sub with a % sigil in the signature, it will fail because the class did not consume the Associatve role:
sub bar(%) { 666 }
say bar(%h);
===SORRY!=== Error while compiling -e
Calling bar(A) will never work with declared signature (%)
I'm not sure why the test for Associative (for the % sigil) and Positional (for #) is not enforced at compile time with the is trait. I would assume it was an oversight, maybe something to be fixed in 6.e.
Quoting the Parameters and arguments section of the S06 specification/speculation document about the related issue of binding arguments to routine parameters:
Array and hash parameters are simply bound "as is". (Conjectural: future versions ... may do static analysis and forbid assignments to array and hash parameters that can be caught by it. This will, however, only happen with the appropriate use declaration to opt in to that language version.)
Sure enough the Rakudo compiler implemented some rudimentary static analysis (in its AOT compilation optimization pass) that normally (but see footnote 3 in this SO answer) insists on binding # routine parameters to values that do the Positional role and % ones to Associatives.
I think this was the case from the first official Raku supporting release of Rakudo, in 2016, but regardless, I'm pretty sure the "appropriate use declaration" is any language version declaration, including none. If your/our druthers are static typing for the win for # and % sigils, and I think they are, then that's presumably very appropriate!
Another source is the IRC logs. A quick search quickly got me nothing.
Hmm. Let's check the blame for the above verbiage so I can find when it was last updated and maybe spot contemporaneous IRC discussion. Oooh.
That is an extraordinary read.
"oversight" isn't the right word.
I don't have time tonight to search the IRC logs to see what led up to that commit, but I daresay it's interesting. The previous text was talking about a PL design I really liked the sound of in terms of immutability, such that code could become increasingly immutable by simply swapping out one kind of scalar container for another. Very nice! But reality is important, and Jonathan switched the verbiage to the implementation reality. The switch toward static typing certainty is welcome, but has it seriously harmed the performance and immutability options? I don't know. Time for me to go to sleep and head off for seasonal family visits. Happy holidays...

create_mutable/2 in SICStus Prolog

The SICStus Prolog manual page on mutable terms states that:
[...] the effect of unifying two mutables is undefined.
Then, why does create_mutable(data,x) fail?
Shouldn't that rather raise an uninstantiation_error?
I cannot think of a situation when above case is not an unintentional programming error (X vs x)... please help!
The short answer to "Why does create_mutable/2 not throw an exception when output unification fails?" is just: Because this was how it was done when the feature was added to SICStus Prolog, and no one has made a strong case for changing this.
One important "difference between the stream created by open/4 and the mutable term created by create_mutable/2" is that open/4 has side-effects that are not undone if the output-unification of the call to open/4 fails.
In this sense, create_mutable/2 is somewhat more like is/2 which also just quietly fails if the output argument is some non-numeric non-variable term, e.g. in x is 3+4. This seems to be the common, and traditional, way of handling output arguments in Prolog.
I agree that a non-variable as second argument is most likely a programming error. The next version of the SICStus IDE, SPIDER, will warn for this (as it already does for is/2).
None of this, nor the example in the question, seems directly related to the cited documentation "[...] the effect of unifying two mutables [...]".

Correct way to use Mockito for JdbcOperation

I am new to Mockito and trying to cover following source code:
jdbcOperations.update(insertRoleQuery,new Object[]{"menuName","subMenuName","subSubMenuName","aa","bb","cc","role"});
In this query is taking 7 string parameters. I have written the mockito test case for the code and it's also covering the source code but I am not sure whether it's the correct way or not.
when(jdbcOperations.update(Mockito.anyString(), new Object[]{Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.anyString(),Mockito.anyString()})).thenThrow(runtimeException);
Please suggest if i am doing it right way or not.
Thanks
As per the docs, you can either use exact values, or argument matchers, but not both at the same time:
Warning on argument matchers:
If you are using argument matchers, all arguments have to be provided
by matchers.
If you do mix them, like in your sample, mockito will complain with something similar to
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at MyTest.shouldMatchArray(MyTest.java:38)
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
In your case you don't seem to care about the array contents, so you can just use any():
when(jdbcOperation.update(anyString(), any())).thenThrow(runtimeException);
If you want to at least check the number of parameters, you can use either
org.mockito.Mockito's argThat(argumentMatcher):
when(jdbcOperation.update(anyString(), argThat(array -> array.length == 7))).thenThrow(runtimeException);
org.mockito.hamcrest.MockitoHamcrest's argThat(hamcrestMatcher):
when(jdbcOperation.update(anyString(), argThat(arrayWithSize(7)))).thenThrow(runtimeException);
If you're interested in matching certain values, you can use AdditionalMatchers.aryEq(expectedArray), or just Mockito.eq(expectedArray) which has a special implementation for arrays, but I fell that the first one expresses your intent in a clearer way.
when(jdbcOperation.update(anyString(), aryEq(new Object[]{"whatever"}))).thenThrow(runtimeException);

How to identify "throw exceptions" in a Java program regarding Integer.parseInt method

I am new to Java and I am having trouble understanding a question. I am asked to select which of the following choices throws an exception. The options are:
1.) Integer.parseInt(" ")
2.) Integer.parseInt("54 ")
3.) Integer.parseInt("")
4.) Integer.parseInt("-54")
5.) Integer.parseInt("54n")
To answer this question, I need some explanations. What does the Integer.parseInt method do? Doesn't it turn an integer into a String? What sort of arguments are illegal to put inside this method. For example, are you allowed to include negative numbers? Strings? Or does it only accept integers?
I was also wondering if you could clarify what "throws an exception" means. I have a rough idea, I think it just means that if there is an error in your program, it gets terminated. Howevere, you can use the "try-catch-finally" method to try and predicate any errors your program would have and write a possible code to fix it?
Sorry for all the questions, I just want to understand this completely.

actionscript 3 How to access 'this' in inline function

I am trying to do something like:
String.prototype.print=function(){trace(??????)}
I can't for the life of me figure out a way to get at the string! Yes I know there are other ways to approach this etc. but...
Not sure what the problem is, using this works fine in anonymous functions.
String.prototype.print=function():String{return "printed "+this;}
var o:Object = "foo";
trace(o.print()); // traces: printed foo
I just tricked the compiler to use an object, because "foo".print() causes
Error: Call to a possibly undefined method print through a reference with static type String.
It looks like you are mixing ActionScript 2 into your ActionScript 3 code. As kapep said, using "this" will work in your example. That is, this is perfectly valid code:
String.prototype.print=function(){trace(this)}
Of course, you are missing a semi-colon but that shouldn't matter:
String.prototype.print=function(){trace(this);} //semi-colon after 'trace(this)'
Depending on your development environment, you might be having trouble viewing trace statements, in general. In Flex Builder, for example, trace statements don't show up at all unless you are in Debug mode. Insert another call to trace to verify that you can see trace statements.
As you said, there are many other ways to approach this, such as extending the String class and adding your "Print" function. If you really can't get this to work, then trying an ActionScript 3 (i.e. Object-Oriented) approach might be your best option.