How to get rid of the compile time error (despite using the import) for assertThrows? (Java, Eclipse Oxygen) - junit5

I am testing out the following code snippet that I found here.
Eclipse Oxygen Version: Oxygen.2 Release (4.7.2) - if that matters
import org.junit.jupiter.api.Assertions;
....
#Test
void exceptionTesting() {
Executable closureContainingCodeToTest = () -> {throw new IllegalArgumentException("a message");};
Assertions.assertThrows(IllegalArgumentException.class, closureContainingCodeToTest, "a message");
}
However, the code doesn't compile.
I am getting the error below:
The method assertThrows(Class, Executable, String) in the type Assertions is not applicable for the arguments (Class, Executable, String) DbHandlerTest.java line 96 Java Problem
Of course my goal is not just to test the above snippet but to write a test for my code. Please help.

I figured out the problem ...
Thanks somuras for the right question.
Following import was wrong
import org.junit.jupiter.api.Executable;
It should have been this:
import org.junit.jupiter.api.function.Executable;

Related

Why is the kotlin-gradle-plugin failing to create a PSIFile from CodeInsightTestFixture.configureByText?

I created an IntelliJ plugin using the template https://github.com/JetBrains/intellij-platform-plugin-template. The template comes with a test that runs on an XML file. I want to create a similar test for a Kotlin file. Here's the template test file plus my added test (test2):
package org.jetbrains.plugins.template
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.psi.xml.XmlFile
import com.intellij.testFramework.TestDataPath
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.PsiErrorElementUtil
#TestDataPath("\$CONTENT_ROOT/src/test/testData")
class MyPluginTest : BasePlatformTestCase() {
fun testXMLFile() {
val psiFile = myFixture.configureByText(XmlFileType.INSTANCE, "<foo>bar</foo>")
val xmlFile = assertInstanceOf(psiFile, XmlFile::class.java)
assertFalse(PsiErrorElementUtil.hasErrors(project, xmlFile.virtualFile))
assertNotNull(xmlFile.rootTag)
xmlFile.rootTag?.let {
assertEquals("foo", it.name)
assertEquals("bar", it.value.text)
}
}
override fun getTestDataPath() = "src/test/testData/rename"
fun testRename() {
myFixture.testRename("foo.xml", "foo_after.xml", "a2")
}
// Here's my test
fun test2() {
val fileText: String = """
package com.loganmay.test
data class MyClass(val myString: String)
""".trimIndent()
val psiFile = myFixture.configureByText("a.kt", fileText)
val xmlFile = assertInstanceOf(psiFile, XmlFile::class.java)
}
}
Without changing the build.gradle file, that test fails with:
Expected instance of: com.intellij.psi.xml.XmlFile actual: com.intellij.psi.impl.source.PsiPlainTextFileImpl
I want it to parse the text as a PsiFile that's also a KtFile. From various sources, I've been led to believe that the fixture is parsing it as a plain text file because the test project doesn't have access to the Kotlin compiler. So, I added:
dependencies {
testImplementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10")
}
to the build.gradle. Then, when I run the test, configureByText throws an exception with a big trace, the root exception of which is:
Caused by: java.lang.Throwable: 'filetype.archive.display.name' is not found in java.util.PropertyResourceBundle#4ecbb519(messages.CoreBundle)
... 53 more
org.jetbrains.plugins.template.MyPluginTest > test2 FAILED
com.intellij.diagnostic.PluginException at ComponentManagerImpl.kt:511
Caused by: java.util.MissingResourceException at Registry.java:164
Does anyone have any insight into what the issue is or know how to resolve it?
Notes:
I also tried importing the kotlin compiler and casting psiFile as KtFile, which produced the same error, an idea I got from here
This project has a test like this that may be working
This post and this post recommend adding the kotlin gradle plugin, which I did
This question seems similar
Yann Cebron replied on the jetbrains help forum with an answer for Java, which also worked for Kotlin.
The solution is to add a dependency to the IntelliJ gradle plugin. The template comes with these lines in the build.gradle:
intellij {
pluginName.set(properties("pluginName"))
version.set(properties("platformVersion"))
type.set(properties("platformType"))
// Plugin Dependencies. Uses `platformPlugins` property from the gradle.properties file.
plugins.set(properties("platformPlugins").split(',').map(String::trim).filter(String::isNotEmpty))
}
So, didn't need to do anything there. In my gradle.properties, I added
platformPlugins = com.intellij.java, org.jetbrains.kotlin
To my plugin.xml, I added:
<depends>com.intellij.modules.java</depends>
<depends>org.jetbrains.kotlin</depends>
I was able to remove
dependencies {
testImplementation("org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.10")
}
from the build.gradle which I mentioned above.
Now, the test works for Java and Kotlin files.

#HystrixProperty cannot be resolved to a type

I have a method marked with #HystrixCommand that has a fallback method defined. I'm trying to add a hystrix property to it so that in case of a timeout it degrades gracefully into a fallback method.
But when I add the #HystrixProperty it shows an error in the STS IDE (3.8.2 Release) saying #HystrixProperty cannot be resolved to a type.
Here is what I'm trying to do:
#HystrixCommand(fallbackMethod="fallbackPerformOperation",
commandProperties={#HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="5000")})
public Future<Object> performOperation(String requestString) throws InterruptedException {
return new AsyncResult<Object>() {
#Override
public Object invoke() {.......
}}}
and this is the error being shown in the IDE:
I'm unable to figure out what the problem is.
Do I need to clear the STS Cache? If so how do I do it?
Thank You.
With in the IDE it is not obvious to suggest the import HystrixProperty class, thus you need to manually import this
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
Then the error should be gone

I am getting error "The method timeouts() is undefined for the type WebDriver.Options"

I am using my implicit wait as below:
//import
import org.openqa.selenium.WebDriver;
//driver declaration
public static WebDriver driver = null;
//implicit wait
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
having error as below:
The method timeouts() is undefined for the type WebDriver.Options
Need help to resolve this.
Nice catch. Seems to me a Bug with Selenium JARS
Here is the Answer to your Question:
As of now your code have only 2 lines. The first line public static WebDriver driver = null; shows no error as you have imported org.openqa.selenium.WebDriver;
In the second line , you are providing Implicit Wait as in driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);. In this case the IDE on which you are working tries to resolve the method timeouts() from org.openqa.selenium.WebDriver which we have already imported. Hence no error should have been shown for timeouts() method.
Hence the following error is not justified:
The method timeouts() is undefined for the type WebDriver.Options
The error should have been shown for either implicitlyWait() method or parameter TimeUnit.
Now, the actual error is with the parameter TimeUnit which is passed within implicitlyWait() method. The IDE clearly suggests about importing java.util.concurrent.
Solution:
The solution is to import java.util.concurrent.TimeUnit; and your code will be error free as follows:
import java.util.concurrent.TimeUnit;
Let me know if this Answers your Question.

How to list `cannot resolve symbol` warnings in groovy code? (IntelliJ)

I want to list all cannot resolve symbol warnings in my groovy code. I set severity level of Groovy->Probable bugs->Access to unresolved expression in my inspection profile to Warning. IntelliJ does highlight the cannot resolve symbol warnings in edit view but it does not list the problems in the list of problems after I run Analyze->Inspect Code....
I'm using IntelliJ IDEA 15.0.2.
Running inspection on the following piece of groovy code responds with a message No suspicious code found though fooo() is highlighted.
class Example {
def foo() {
fooo() // highlighted as `Cannot resolve symbol 'fooo'`
}
}
You are looking for static compilation behavior. Please use #CompileStatic for it
import groovy.transform.CompileStatic
#CompileStatic
class Example {
def foo() {
fooo() // highlighted as `Cannot resolve symbol 'fooo'`: shows as error in IJ14
}
}

toolprovider.getsystemjavacompiler() returns null

First, I am seeing a lot of questions about the use of the JavaCompilerAPI, I want to clarify that I am creating an on-line simulation builder that takes too many inputs from the user to precreate classes. That is why I am using a java compiler in order to write the classes using the user's inputs.
As for my problem, I have tested with some basic compiler programs, and am presently working of code found here: Dynamic Compiling Without Create Physical File
The compilation of the code is successful, however when I run the code,
ToolProvider.getSystemJavaCompiler();
returns null.
From other entries I understand one cause might be that the default java.home is JRE, so I added the line where I set java home to my JDK version:
System.setProperty("java.home", "C:\\Program Files (x86)\\Java\\jdk1.7.0_51;");
I have also added tools.jar to the folder with my program, and called the program specifying tools.jar in the classpath like so:
java -cp ".;tools.jar" Compiler
These approaches have not changed anything. Any ideas about what might be the problem?
import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.*;
public class Compiler {
static final Logger logger = Logger.getLogger(Compiler.class.getName());
static String sourceCode = "class HelloWorld{"
+ "public static void main (String args[]){"
+ "System.out.println (\"Hello, dynamic compilation world!\");"
+ "}"
+ "}";
public void doCompilation() {
System.out.println(System.getProperty("java.home"));
System.setProperty("java.home", "C:\\Program Files (x86)\\Java\\jdk1.7.0_51;");
System.out.println(System.getProperty("java.home"));
SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject("HelloWorld",sourceCode);
JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject};
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
System.out.println(compiler);
StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
...