Console.ReadLine() throws nullpointer exception in Groovy - intellij-idea

I started learning groovy yesterday and have been enjoying it thus far until I got to the part of the book where I have to take in inputs from the user using console().readLine() but I keep getting this error
Caught: java.lang.NullPointerException: Cannot invoke method readLine() on null object java.lang.NullPointerException: Cannot invoke method readLine() on null object
at com.usl.NewCodes.run(NewCodes.groovy:30)
I have tried it in intelliJ both as a groovy script and in a class. I even went on to try it in the groovyConsole yet it still throws an error.
Here is the code
print("What is your name ");
def fName = System.console().readLine()
println("Hello" + fName)
Thanks

If you are using any IDE for Groovy, the input / output console will not be available to you hence throwing null pointer exception so, you can use the following, If you are using Intellij enable groovy console from Tools -> groovy console for I/O.
println "What is your name?"
println "Your name is:"+System.in.newReader().readLine()

Related

Why am I getting "java.lang.NoClassDefFoundError: Could not initialize class io.mockk.impl.JvmMockKGateway" when using quarkusDev task in IntelliJ?

I am using Gradle 7.5, Quarkus 2.12.3 and mockk 1.13.3. When I try to run quarkusDev task from command line and then start continuous testing (by pressing r), then all tests pass OK.
However, when I do the same as from IntelliJ (as gradle run configuration), all tests fail with error:
java.lang.NoClassDefFoundError: Could not initialize class io.mockk.impl.JvmMockKGateway
How can I fix that?
Masked thrown exception
After much debugging I found the problem. The thrown exception actually originates in HotSpotVirtualMachine.java and is thrown during attachment of ByteBuddy as a java agent. Here is the relevant code;
// The tool should be a different VM to the target. This check will
// eventually be enforced by the target VM.
if (!ALLOW_ATTACH_SELF && (pid == 0 || pid == CURRENT_PID)) {
throw new IOException("Can not attach to current VM");
}
Turning check off
So the check can be turned off by setting ALLOW_ATTACH_SELF constant to true. The constant is set from a system property named jdk.attach.allowAttachSelf:
String s = VM.getSavedProperty("jdk.attach.allowAttachSelf");
ALLOW_ATTACH_SELF = "".equals(s) || Boolean.parseBoolean(s);
So, in my case, I simply added the following JVM argument to my gradle file and tests started to pass:
tasks.quarkusDev {
jvmArgs += "-Djdk.attach.allowAttachSelf"
}

Testng Change Methode status from passed to fail

In my code i catch the error that might occure and give them a reporter.log(); which contain the problem that happened since i dont want my code to crash after one probleme found the probleme with this is that i always get Passed as a result even though my Report Log contains a failed step.
What i want is in case that reporter.log(); gonna be written i want to change the status of the methode into failed.
The report that i write :
String FormatMessageError = "<font color='red'></br><img src='"+ Bad +"'/>-";
Reporter.log(FormatMessageError +" Wasnt abel to connect</font>");
What i tried :
I used this :
Reporter.getCurrentTestResult().setStatus(ITestResult.FAILURE);
but the status stay as passed After that i tried this :
SoftAssert SAAjoutPanier = new SoftAssert();
SAAjoutPanier.assertEquals(ValidationOfPurchase,false,FormatMessageError +" Wasnt abel to connect</font>");
with : SAAjoutPanier.assertAll(); in the end of my #test as you can imagine it didn't work
Then i tried this :
Throwable throwable = new Throwable("One or more tests in this group has failed");
throwable.setStackTrace(new StackTraceElement[0]);
Reporter.getCurrentTestResult().setThrowable(throwable);
But it gives just a message but the status it self is still passed.
Can some one help me with this probleme ty !
MSTest has the same limitation. The solutuon I used, just throw a real error at the end.
throw new Exception("some test steps failed");
If that works, keep a list somewhere with the real errors and inserts in the error you throw.

How to fail Velocity template processing with tracable message

Having:
Velocity template or macro
some object
How to validate the object (#if) and fail (stop further processing) in a way that is easily tracable to the place of failure (like throwing exception in Java).
I am looking for something like this:
#if ( ! $context.treasureMap.containsKey('gold'))
#fail('no golden treasure here')
#end
Background
I am writing a maven site page. The velocity context is injected by maven and contains POM information. I want to test existence of some information from effective pom. When the information is not available, I want to fail.
Requirements
fail Velocity processing > fail site generation > fail maven build.
error message should lead to the place of failure so the site should be fixed
preferably no configuration (no extensions, just constructs/tools contained in plain Velocity)
Tried
Strict Reference Mode
Unwanted configuration, do not want to fail on every occasion.
#evaluate('#end') aka syntax error
(Chose #end as most descriptive to my intent) Basically what I want. Fails the processing and maven build but the error message does not lead back to failure location:
ParseException: Encountered "#end" at line 1, column 1..
You need to make a method call which produce exception.See explanation:
The only place where one could run into trouble within Velocity is if there is a call to a method which throws an exception during runtime. For example, this VTL defines a String $foo and then attempts to call its substring() method on it would throw an IndexOutOfBoundsException:
#set ($foo = "bar")
#set ($bar = $foo.substring(0,10))
When the exception is thrown, the parser will stop processing and throw that exception up the stack tree where it can be caught in the method that caused the parser to execute. At that point, the exception can be handled gracefully.

F#: UnitTest case failled

Consider i have a function like newConvert. I am sopposed to recieve an error for newCovertor("IL") . To generate this erorr: I used failwith "Invalid Input"
The erorr is :
System.Exception: Invalid Input
> at FSI_0160.inputChecker(FSharpList`1 numberList) in C:\Users\Salman\Desktop\coursework6input\itt8060-master\coursework6input\BrokenRomanNumbers\Library1.fs:line 140
at FSI_0160.newCovertor(String romanNumber) in C:\Users\Salman\Desktop\coursework6input\itt8060-master\coursework6input\BrokenRomanNumbers\Library1.fs:line 147
at <StartupCode$FSI_0165>.$FSI_0165.main#() in C:\Users\Salman\Desktop\coursework6input\itt8060-master\coursework6input\BrokenRomanNumbers\newtest.fs:line 32
Stopped due to error
I used FsUnit and Nunit, they are loaded and installed and working rightly.
Then I made a tes for it using
[<TestFixture>]
type ``Given a Roman number15 ``()=
[<Test>]
member this.
``Whether the right convert for this number must be exist``()=
newCovertor("IL") |> should equal System.Exception
I cannot understand!! The function fails rightly, but the test does not accept it, so why??????
newCovertor does not produce a System.Execption - it throws it - so you never get to the should equal ... part
to catch the exception with FsUnit you have to wrap it as an action:
(fun () -> newCovertor("IL") |> ignore) |> should throw typeof<System.Exception>
also see the really good docs - there are quite a few ways to achieve this
The reason your version is not working is that NUnit will normaly mark a test as failed exactly when a exception is thrown inside the test-methods body - which you do.
If you wrap it in an action than the should throw can choose to execute this delayed action inside try ... match block to catch the expected exception and filter it out (or in this case throw an exception if there where none)
btw: just like in C#/VB.net you can also use the ExpectedExceptionAttribute from NUnit on the method level if you like - this way the test-framework will handle it for you.

Writing Codeception CLI test; want to throw exception but not have it fail the test

I forked Codeception/Codeception and added a Command module check that throws an exception.
When testing, this exception causes the test to fail but I'm running a test to force the exception and failure, to make sure it catches it.
Here's the edit to src/Codeception/Command/GenerateSuite.php
if ($this->containsInvalidCharacters ($suite)) {
throw new \Exception("Suite name '{$suite}' contains invalid characters. ([A-Za-z0-9_]).");
}
When updating tests/cli/GenerateSuiteCept.php when I run the command $I->executeCommand('generate:suite invalid-suite'); it fails because I'm throwing the exception in src/Codeception/Command/GenerateSuite.php in the first place.
Here is the addition to tests/cli/GenerateSuiteCept.php:
$I->executeCommand('generate:suite invalid-dash-suite');
When I run it, it says it failed. However, I want it to pass because I'm deliberately adding the dash to verify it catches invalid characters. What is the best way to do that? I'm wary of a try/catch block in these tests. I'm not sure if that is the best way to do that.
After looking at the other Codeception tests, I found this to be a better way than throwing an exception:
if ($this->containsInvalidCharacters ($suite)) {
$output->writeln("<error>Suite name '{$suite}' contains invalid characters. ([A-Za-z0-9_]).</error>");
return;
}
So I modified the test to:
$I->expect ('suite is not created due to dashes');
$I->executeCommand('generate:suite invalid-dash-suite');
$I->seeInShellOutput('contains invalid characters');