Test fails after migration from mockito-core:2.23.4 to mockito-core:3.4.6 - mockito

I migrated to mockito-core:3.4.6. After that, some of my methods does not succeed anymore.
...
#SpyBean
MyInstance myInstance;
...
doAnswer(params -> params.getArgument(0)).when(myInstance).myMethod(any());
I get this error:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();
I tried different ways like lenient mode
lenient().doAnswer(params -> params.getArgument(0)).when(myInstance).myMethod(any());
Also I tried BDDMockito style:
given(myInstance.myMethod(any(UsedClass.class))).willReturn(usedClassResponse);
None of them worked.
Any idea please ?

Related

NUnit Attribute to simulate condition-based Assert.Inconclusive with custom message text

I have some tests that depend on a certain thing being true (access to the internet, as it happens, but that isn't important and I don't want to discuss the details of the condition).
I can very easily write a static helper method which will test the (parameterless) condition and call Assert.Inconclusive("Explanatory Message") if it's true/false. And then call that at the start of each Test which has this requirement.
But I'd like to do this as an Attribute, if possible.
How, in detail, do I achieve that, in NUnit?
What I've tried so far:
There's an IApplyToTest interface, exposed by NUnit, which I can make my Attribute implement, and will allow me to hook into the TestRunner, but I can't get it to do what I want :(
That interface gives me access to an NUnit.Framework.Internal.Test object.
If I call:
test.RunState = RunState.NotRunnable;
then I get something equivalent to Assert.Fail("").
Similarly RunState.Skipped or RunState.Ignored give me the equivalent of Assert.Ignore("").
But none of these are setting a message on the Test, and there's no test.Message = "foo"; or equivalent (that I can see).
There's a test.MakeInvalid("Foo") which does set a message, but that's equivalent to Assert.Fail("Foo").
I found something that looked promising:
var result = test.MakeTestResult();
result.SetResult(ResultState.Inconclusive, "Custom Message text");
But that doesn't seem to do anything; the Test just Passes :( I looked for a test.SetAsCurrentResult(result) method in case I need to "attach" that result object back to the test? But nothing doing.
It feels like this is supposed to be possible, but I can't quite figure out how to make it all play together.
If anyone can even show me how to get to Skipped + Custom Message displayed, then I'd probably take that!
If you really want your test to be Inconclusive, then that's what Assume.That is there for. Use it just as you would use Assert.That and the specified constraint fails, your test result will be inconclusive.
That would be the simplest answer to your question.
However, reading the things you have tried, I don't think you actually want Inconclusive at least not as it is defined by NUnit.
In NUnit, Inconclusive means that the test doesn't count because it couldn't be run. The result basically disappears and the test run is successful.
You seem to be saying that you want to receive some notice that the condition failed. That makes sense in the situation where (for example) the internet was not available so your test run isn't definitive.
NUnit provides Assert.Ignore and Warn.If (also Warn.Unless) for those situations. Or you can set the corresponding result states in your custom attribute.
Regarding implementation... The RunState of a test applies to it's status before anyone has even tried to execute it. So, for example, the RunState may be Ignored if someone has used the IgnoreAttribute or it may be NotRunnable if it requires arguments and none are provided. There is no Inconclusive run sttate because that would mean the test is written to be inconclusive all the time, which makes no ssense. The IApplyToTest interface allows an attribute to change the status of a test at the point of discovery, before it is even run, so you would not want to use that.
After NUnit has attempted to run a test, it gets a ResultState, which might be Inconclusive. You can affect this in the code of the test but not currently through an attribute. What you want here is something that checks the conditions needed to run the test immediately before running it and skips execution if the conditions are not met. That attribute would need to be one that generates a command in the chain of commands that execute a test. It would probably need to implement ICommandWrapper to do that, which is a bit more complicated than IApplyToTest because the attribute code must generate a command instance that will work properly with NUnit itself and with other commands in the chain.
If I had this situation, I believe I would use a Run parameter to indicate whether the internet should be available. Then, the tests could
Assume.That(InternetIsNotNeeded());
silently ignoring those tests or fail as expected when the internet should be available.

How can I prevent a kotlin extension from being used on my objects?

For special threading issue in my app I created an object with a runOrQueue() method which accepts a block. Here is a simplified version for illustrative purpose:
class SpecialThread {
fun runOrQueue() {}
}
The problem is that when I'm trying to write code using this method, the IDE autocompletes first to a Kotlin extension method named run(), defined in the standard library:
#kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {…}
Here is a screen capture of the IDE autocompletion:
This is especially dangerous in the context of my app, since both run and runOrQueue would have similar results (both running a block of code), but the standard library version would crash in certain situations, wrapped properly in the runOrQueue method.
Is there any way I can explicitly disable the possibility of using the run extension on this particular object of my creation? In fact, reviewing the code I wrote myself, I've already mistakenly used run twice instead of the longer method name, and that is not good.
If you really really don't want to rename your method, and you're absolutely sure that you'll never use the run function...
You can actually exclude any method from autocompletion by clicking the intention action icon next to the suggestion:
In Settings, you can find this under Editor -> General -> Auto Import, and then Exclude from import and completion. For example, to exclude the built-in run function, you'd add this entry, either via the intention mentioned above, or manually:
If you make this project scoped, the exclusion can be checked into VCS as well, you'll find it under .idea/codeInsightSettings.xml, which would have these corresponding contents to exclude run, pretty self explanatory:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaProjectCodeInsightSettings">
<excluded-names>
<name>kotlin.run</name>
</excluded-names>
</component>
</project>
While the comments to rename the method are worthy, I kept trying things to prevent the wrong code from compiling and managed to reach a compromise, which might be generalizable to other possible symbol clashes in the future.
First, in order to confuse the compiler, a very similar method is added to the object:
#Deprecated(level = DeprecationLevel.ERROR,
message = "This is not the method you are looking for (waves hand)",
replaceWith = ReplaceWith("runOrQueue()"))
fun <T, R> run(block: T.() -> R): R {
TODO("Don't use this")
}
This is not exactly the same as the standard library run(), so when you start typing in the IDE you still get one suggestion for the standard library, and another for the object method. Fortunately, even if the autocomplete version is used, since there are two very similar run() methods, the compiler will complain about ambiguity.
In fact, after adding this method and rebuilding the source, the compiler caught two more instances of the mistake:
e: PasswordPresenter.kt: (181, 49): Using 'run(T.() -> R): R' is an error. This is not the method you are looking for (waves hand)
e: PasswordPresenter.kt: (181, 49): Type inference failed: Not enough information to infer parameter T in fun <T, R> run(block: T.() -> R): R
Please specify it explicitly.
e: PasswordPresenter.kt: (258, 33): Using 'run(T.() -> R): R' is an error. This is not the method you are looking for (waves hand)
e: PasswordPresenter.kt: (258, 33): Type inference failed: Not enough information to infer parameter T in fun <T, R> run(block: T.() -> R): R
Please specify it explicitly.
Not the prettiest in the world, but it comes close and gets the job done. Or as Sally Amaki would say, fake it till you make it.
I'm afraid this isn't really possible as run is in the std library and is defined as an extension on any type:
/**
* Calls the specified function [block] with `this` value as its receiver and returns its result.
*/
#kotlin.internal.InlineOnly
public inline fun <T, R> T.run(block: T.() -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block()
}
Some options:
For the parts of your codebase where you don't want run to be used, write it in Java instead (as Kotlin and Java are completely interporable). This solution is not ideal.
Don't write run when you mean runOrQueue.
Write a custom lint extension to flag usages of run as a warning or an error:
https://developer.android.com/studio/write/lint
EDIT:
Forpas gave another good solution to rename your function to queueOrRun. The problem with this is the OR, I imagine your method attempts to run and only falls back to queue if that is not possible, therefore changing the name of the function will make it less clear what it does.

Azure Function: "Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information"

I have an F# Azure Function that is failing, in a bizarre way, and don't know how to approach fixing the issue. I created a minimum repro of the actual case below. The test function is manually triggered and uses FSharp.Compiler.Service as a dependency, as specified in the project.json below:
{
"frameworks": {
"net46":{
"dependencies": {
"FSharp.Compiler.Service": "11.0.6"
}
}
}
}
The run.fsx file looks like this:
open System
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.Ast
open Microsoft.FSharp.Compiler.Interactive.Shell
let Run(input: string, log: TraceWriter) =
// code here that uses FsiEvaluationSession
// and runs just fine
log.Info "I RAN"
So far, so good. The part that baffles me is that if I add the following function above Run,
// same dependencies as before
open Microsoft.FSharp.Compiler.Interactive.Shell
let foo (longIdent:LongIdent) =
// version 1
// "FOO"
// version 2
// longIdent.ToString ()
// version 3
longIdent |> List.map string
let Run(input: string, log: TraceWriter) =
// same as before
Uncommenting section 1 alone works fine, uncommenting section 2 alone works fine, uncommenting section 3 causes hell to break loose. The function compiles, but running it causes the following exception:
Exception while executing function: Functions.fsc-1. mscorlib: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
... which is puzzling to me, because
foo isn't even called anywhere
the signature and the 2nd version both use LongIdent, so this type doesn't seem to be the source of the problem.
Any suggestion on how to approach the problem, and what the problem itself might be, would be very appreciated - I don't even know where to start, and the same code runs perfectly fine in a local script.
I believe the reason for this is that Azure Functions SDK depend on FSharp.Compiler.Service (FCS) version 9.0.1. This means that when you try to load a different version of FCS, you will get the already loaded version 9.0.1.
This works as long as the public API of the FCS version you are using matches the public API of version 9.0.1, but when there are differences, it will crash, because your code assumes that the public API looks different. I suppose this might be triggering the issue here, although I'm not 100% sure how (possibly, LongIdent is now a different thing than it was in version 9.0.1?)
The very same issue used to happen with FAKE, which also bundles FCS and prevented loading of different versions. One of the options is to rename the assembly to avoid the clash.
I also got the same error, I solved it by doing the following workaround, please refer if it works for you also.
Right-click on the Project and select properties.
Goto Debug tab and create a profile with the reference to the below
screenshot.
Note: Replace UserName with your username.

Could someone explain this coffeescript syntax to me?

I'm extending a chrome extension that is written in coffeescript and have come across this syntax:
Commands =
init: ->
for command, description of commandDescriptions
#addCommand(command, description[0], description[1])
availableCommands: {}
keyToCommandRegistry: {}
I'd just like to check the difference between this syntax and a class (which would be like this, hypothetically):
class Commands
init: ->
for command, description of commandDescriptions
#addCommand(command, description[0], description[1])
availableCommands: {}
keyToCommandRegistry: {}
Is it just that the former doesn't have a prototype? am I right in thinking that it's alright to call the methods on the Commands in the top, as in Commands.init(). The project I'm working in seems to use both syntaxes so I would like to be sure I understand the implications of each before I use one or another.
Thanks.
The primary implication of the first Command is that it is an Object, not a Function, so there is no way to stamp out instances of it directly.
It is a bit confusing that its init method includes commandDescriptions (which I can only expect is declared somewhere else) and #addCommand, which is not attached to the Command object. If Command didn't have #addCommand, I would expect that it is a singleton. But as a method that is not declared on Command is expected to be present, it looks like the group of functionality in Command is meant to be mixed into another class.
Edit:
To clarify, objects can have #variables. In the init function, you would reference availableCommands or keyToCommandRegistry as #availableCommands and #keyToCommandRegistry. However, in this particular example, #addCommand is not declared anywhere. I would have expected it to be declared as part of the Command object declaration, like:
CommandsA =
init: ->
for command, description of commandDescriptions
#addCommand(command, description[0], description[1])
availableCommands: {}
keyToCommandRegistry: {}
addCommand: (command, descriptionInfo, otherDescriptionInfo) ->
#Does some stuff
If you can find where addCommand is declared, it would help in understanding how Command is intended to be used.
Also of note: since Command is an object and not a class, the availableCommands and keyToCommandRegistry objects can be thought of as static class variables.

Common php functions in hack

I decided to start a new project to get into hacklang, and after fixing some if the problems I initially ran into transitioning from php habits, I ran into the following errors:
Unbound name: str_replace
Unbound name: empty
Doing some research I found that this is due to using 'legacy' php which isn't typechecked, and will error with //strict.
That's fine and all, empty() was easy enough to replace, however str_replace() is a bit more difficult.
Is there an equivalent function that will work with //strict? Or at least something similar.
I'm aware that I could use //decl but I feel like that defeats the purpose in my case.
Is there at least any way to tell which functions are implemented in hack and which are not in the documentation as I couldn't find one?
For reference (though it isn't too relevant to the question itself), here is the code:
<?hh //strict
class HackMarkdown {
public function parse(string $content) : string {
if($content===null){
throw new RuntimeException('Empty Content');
}
$prepared = $this->prepare($content);
}
private function prepare(string $contentpre) : Vector<string>{
$contentpre = str_replace(array("\r\n","\r"),"\n",$contentpre);
//probably need more in here
$prepared = Vector::fromArray(explode($contentpre,"\n"));
//and here
return $prepared;
}
}
You don't need to change your code at all. You just need to tell the Hack tools about all the inbuilt PHP functions.
The easiest way to do this is to download this folder and put it somewhere in your project. I put it in a hhi folder in the base of my project. The files in there tell Hack about all the inbuilt PHP functions.
Most of them don't have type hints, which can lead to Hack thinking the return type of everything is mixed instead of the actual return, that is actually correct in most cases as, for example, str_replace can return either a string or a bool. However, it does stop the "unbound name" errors, which is the main reason for adding them.

Resources