spring junits are not reconized in eclipse - eclipse

I have a test case which looks like the following
#ContextConfiguration(locations = { "classpath:chartContext-test.xml" })
#Component("allocationChartTest")
public class ChartServiceUnitTest extends AbstractTestNGSpringContextTests {
and I have imports which look like the following
org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
so basically i am using spring junits it is nothing to do with junit 4 or 3
When i right click on the class it does not give an option called run as junit
not sure what needs to be added scr/mian/java and src/main/test both are included in my source..
Can some one give an idea why it is is giving me an option ..

Why does your test class have the #Component annotation? Anyhow, you need to install TestNG in Eclipse. Are you familiar with tutorials such as this one: http://java.dzone.com/articles/spring-testing-support-testng?

Related

intellij Junit generate test classes for scala

Hi I am using scala with Junit.
Every time I want to generate a test class CTRL + SHIFT + T it always generates a java class and I always need to reformat the class and the code inside it.
How can I implement this feature in Intellij?
I'd like to generate a test class like this:
package combiner.impl
import org.junit.Test;
import org.junit.Assert._
class NextploraWeboDataFrameCombinerImplTest {
#Test
def combineDataFrames() {
}
}
While generating the test you should select ScalaTest testing library. The default template of generated file can be changed in Preferences | Editor | File and Code Templates | Code | ScalaTest Class.

How to fix "Test Class not found in selected project" in cucumber junit

I am new to Cucumber. I created a simple cucumber script to launch google in browser. I properly created features, steps and runner classes. When I ran the runner class, the junit result shows green but the scenario not executed (browser not launched). On checking the results and trying to double-click, it says "Test Class not found in selected project".
I already tried changing order of JRE in Build path->Order&Export option. This is Eclipse.JUnit result image
This is the runner class:
package Runners;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(features="Features/ChromeTest.feature",glue= {"src/test/java/Steps"})
public class ChromeRunner {
}
I assume you keep your features files also within src/test/java path
if so,please try running with
#CucumberOptions(features="src/test/java/features",glue="steps")
or
#CucumberOptions(features="src/test/java/features",glue="src/test/java/steps")
**assuming that you have created features and steps as package inside src/test/java path

Eclipse keep saying "No tests found with test runner JUnit 5"

I am using Eclipse Oxygen.3 Release (4.7.3). The following is my JUnit test class:
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
class MyMathTest {
MyMath myMath = new MyMath();
#Before
public void before() {
System.out.println("Before");
}
#After
public void after() {
System.out.println("After");
}
#Test
public void testSum_with3numbers() {
System.out.println("Test1");
int result = myMath.sum(new int[] {1,2,3});
int expected = 6;
assertEquals(expected, result);
}
#Test
public void testSum_with1numbers() {
System.out.println("Test2");
int result = myMath.sum(new int[] {3});
int expected = 3;
assertEquals(expected, result);
}
#BeforeClass
public static void beforeClass() {
System.out.println("Before class");
}
#AfterClass
public static void afterClass() {
System.out.println("After class");
}
}
When I run this Junit test, eclipse keeps popping up dialog telling "No tests found with test runner 'JUnit 5'". Why?
Your test class is currently based on JUnit 4 since it uses annotations from the org.junit package.
Thus, to get it to run as a JUnit 4 test class in Eclipse, you need to select the JUnit 4 Runner in the "Run Configuration". Click on the tiny arrow (pointing down) next to the green circle with a white arrow in it (at the top of the Eclipse IDE). There you should see your test class, and by selecting that you can switch between the JUnit 4 and JUnit 5 runners.
On the other hand, if your goal is to write a test using JUnit Jupiter (i.e., the programming model for JUnit 5), you'll need to switch from annotations in org.junit to org.junit.jupiter.api.
I had the same error, after trying everything, I have realized that the JUnit library wasn't added. So after adding it, tests worked as intended.
This happened to me because my test method was declared as private and JUnit could not detect it. After I made it public it worked as expected, of course with #Test annotation.
In Eclipse 2019-09 (4.13) is a bug that can cause the "No tests found with test runner 'JUnit 5'" error:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=551298
I added the following dependency to my project and it worked for me:
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-commons</artifactId>
<version>1.5.2</version><!--$NO-MVN-MAN-VER$-->
<scope>test</scope>
</dependency>
the test class is not public, make it public and it should work
Take a look back to your imports.
You imports import org.junit.Test; (Used for run test cases with JUnit 4)
You need to import import org.junit.jupiter.api.Test; to run tast case with JUnit5.
You are using JUnit 4 annotations with JUnit 5 dependencies.
If you want to use JUnit 5 you should replace:
#Before with #BeforeEach
#After with #AfterEach
#BeforeClass with #BeforeAll
#AfterClass with #AfterAll
#Ignore with #Disabled
Here is more about JUnit 5 annotations https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations/
Right click the java file and choose:
Build Path -> Configure Build Path -> Java Build Path.
Choose the tab Libraries in Java Build Path, On the right side tab choose Add Library.
Select JUnit and click Next.
Choose JUnit 5 in JUnit Library version dropdown and click finish.
Now run the Test with Junit Test, it will work.
This procedure worked for me.
right click and run as -> config-> make this change and run it will works cheers!!.
My 2 cents:
Right click on project -> Configure -> Add module-info -> Give some random name.
It should automatically add there a requires in the JUnit package, if not, then manually add this:
requires org.junit.jupiter.api;
And it will magically work!
* tested on Eclipse 2018-12
My issue was that, Run works fine, debug throws this error.
I was getting this merely because of low memory in the system. Ideally, eclipse couldn't launch the debug session due to low memory in the system. Error message thrown is confusing.
Hope it helps someone!
In my current case, I encountered this error when testing the pact verification on the Service Provider side.The error was thrown because the Pact Broker doesn't have any pact to test against the Service Provider.
Visit the pact broker and ensure that there is at least one pact to test with.
I had the same problem with an Eclipse (2020-09) non-Maven project. None of the proposed solutions worked, but changing the compiler from 9.0.4 to 15.0.1 did.
I did that by selecting Preferences > Java > Installed JREsand checking the box next to jdk-15.01. You may need to install a recent JDK if none are shown.
Adding the JUnit vintage dependency fixed the issue for me.
https://junit.org/junit5/docs/current/user-guide/#migrating-from-junit4-running
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>

ScalaTest Plus not recognizing tests

I've been tasked to update and write a series of tests on an app in Scala Play, a language and framework I'm unfamiliar with. Part of what I'd like to do is integrate the ScalaTestPlus library. To get started I have been following the following tutorial:
https://www.playframework.com/documentation/2.2.x/ScalaTestingWithScalaTest
Unfortunately I am not getting very far. I have added a new unit test file to the tests folder:
import org.scalatestplus.play._
class StackSpec extends PlaySpec {
"A Test" must {
"pass" in {
assert(1 == 1)
}
"Fail" in {
assert(1 != 1)
}
}
}
and I have updated my build.sbt to include the scalatestplus library
"org.scalatestplus" % "play_2.37" % "1.2.0" % "test"//,
Using Activator, I am trying to run my test file with test-only. Everything compiles without errors, but activator is not finding any tests
[info] No tests were executed.
I don't believe the issue is with activator, since I can run old test files (from the previous engineer) using the test and test-only commands. A quick sample of one of the previous (working) test files:
import java.util.concurrent.TimeUnit
import com.sun.xml.internal.bind.v2.TODO
import scala.collection.JavaConverters._
import controllers.Application
import models.{Item, PriorityBucket}
import play.api.test._
class WebSpec extends PlaySpecification {
"Home page" should {
"do something" in new WithSeleniumDbData(TestUtil.testApp) {
Redacted.deleteAll()
val ObId = TestUtil.create(Some(PriorityBucket.Low),
Some(Application.ENGLISH))
val item = Item.find(ItemId).get
browser.goTo("/")
browser.await().atMost(2,
TimeUnit.SECONDS).until(Selectors.all_obs).isPresent
}
Any ideas where I've gone astray? Thanks in advance for the help!
I am using scala 2.11
I am using play 2.3.7
EDIT: Possibly relevant, I switched the extension from PlaySpec to FlatSpec and saw the following error when compiling:
SampleSpec.scala:10: value in is not a member of String
[error] "pass" in {
I made sure to import FlatSpec as well, which has me a bit confused--is FlatSpec a member of ScalaTest but not a member of ScalaTestPlus, I don't see why else the compilation would fail.
UPDATE: To further investigate the issue I spun up a brand new Play app and copied over my sample test. After some tooling around with versions I've been able to get my test to run on the activator test command with the rest of the suite. Unfortunately, any other commands like test-only are still returning no tests run.
For those following I ran across the issue...the class name in this case needed to be identical to the file name, otherwise test-only cannot locate it.

'Unable to load a Suite class' while running ScalaTest in IntelliJ

I'm having some issues today with running a simple TestKit test in Intellij. The tests are for Scala code (I have the Scala plug-in for Intellij) and are based on Ray Roestenburg's example.
The Intellij project was created using a "Maven Module" which I then added all the dependencies to and created my project. The tests are located in the following place:
ActorBlast/src/test/scala/basicTest.scala
I'm basically "right-clicking" on the test and selecting "Run". What I get is the following error:
"C:\Program Files\Java\jdk1.7.0_25\bin\java" -Didea.launcher.port=7540...
Testing started at 2:29 PM ...
Unable to load a Suite class. This could be due to an error in your runpath.
Missing class: BasicActorSpec java.lang.ClassNotFoundException:
BasicActorSpec at
java.net.URLClassLoader$1.run(URLClassLoader.java:366) at
java.net.URLClassLoader$1.run(URLClassLoader.java:355) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader.findClass(URLClassLoader.java:354) at
java.lang.ClassLoader.loadClass(ClassLoader.java:424) at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at
java.lang.ClassLoader.loadClass(ClassLoader.java:357) at
org.scalatest.tools.Runner$$anonfun$35.apply(Runner.scala:2393) at
org.scalatest.tools.Runner$$anonfun$35.apply(Runner.scala:2391) at
scala.collection.TraversableLike$$anonfun$filter$1.apply(TraversableLike.scala:264)
at scala.collection.immutable.List.foreach(List.scala:318) at
scala.collection.TraversableLike$class.filter(TraversableLike.scala:263)
at scala.collection.AbstractTraversable.filter(Traversable.scala:105)
at
org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:2391)
at
org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1006)
at
org.scalatest.tools.Runner$$anonfun$runOptionallyWithPassFailReporter$2.apply(Runner.scala:1005)
at
org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:2659)
at
org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1005)
at org.scalatest.tools.Runner$.run(Runner.scala:845) at
org.scalatest.tools.Runner.run(Runner.scala) at
org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2(ScalaTestRunner.java:144)
at
org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606) at
com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Process finished with exit code 0
I can't figure out what this means. I've done a lot of searching but can't seem to find an answer. Note that the class the runner is complaining about not finding is the class I'm trying to test/run. The basicTest.scala looks like this:
// Testing specific imports
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.{ShouldMatchers, WordSpecLike, BeforeAndAfterAll}
import akka.testkit.{TestKit, DefaultTimeout, ImplicitSender}
// Actor specific imports
import akka.actor.{ActorRef, Actor, ActorSystem, Props}
// Misc. needed imports
import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
// In order to run tests in this module you need to use JUnitRunner (as per scalatest.org)
#RunWith(classOf[JUnitRunner])
class BasicActorSpec extends TestKit(ActorSystem("BasicActorSpec", ConfigFactory.parseString(BasicActorSpec.config)))
with DefaultTimeout with ImplicitSender with WordSpecLike with ShouldMatchers with BeforeAndAfterAll {
import BasicActorSpec._
val echoRef = system.actorOf(Props[EchoActor])
val forwardRef = system.actorOf(Props[ForwardActor])
override def afterAll {
shutdown(system)
}
/**
* The actual tests...
*/
"An EchoActor" should {
"Respond with the same message it receives" in {
within(500 millis) {
echoRef ! "test"
expectMsg("test")
}
}
}
"A Forwarding Actor" should {
"Forward a message it receives" in {
within(500 millis) {
forwardRef ! "test"
expectMsg("test")
}
}
}
}
/**
* Companion object of test class
*/
object BasicActorSpec {
val config =
"""
|akka {
| loglevel = "Warning"
|}
""".stripMargin
/**
* Classes of Actors used in testing
*/
class EchoActor extends Actor {
def receive = {
case msg => sender ! msg
}
}
class ForwardActor(next: ActorRef) extends Actor {
def receive = {
case msg => next ! msg
}
}
}
Any help as to why I am getting this error would be GREATLY appreciated.
Run build the project - It helped me to resolve that issue that could have happened to me when I cleared Cache IDEA :) while trying to tackle another issue
This is how I solved same exception:
--> Right click on your project folder in IDE:
--> Click Add Framework Support
--> Then Check Scala
--> Click OK
My project already had the setup as mentioned by #Rustam Aliyev. Still was getting the same exception. Rebuilding the project did not help either. Quite weird ; but Restarting the IDE helped to solve the issue
This issue happened to me recently when I was trying to run tests in an inherited Scala project using IntelliJ IDEA 2018 (Community Edition). Below steps helped me to fix it:
File → Project Structure → {Choose specific module} → "Paths" tab → Select "Use module compile output path" → Modify "Test output path" to point to test-classes folder. For example:
Output path: /home/rustam/IdeaProjects/{project}/{module}/target/scala-2.12/classes
Test output path: /home/rustam/IdeaProjects/{project}/{module}/target/scala-2.12/test-classes
IntelliJ does not like multiple Scala classes defined in one file, so make sure the test class is named the same as the test file and nest other helper classes, which you can refactor later as necessary.
I met this issue when I used Gatling
I fix it by replacing gatling-classes to test-classes on File -> Project Structure -> Modules -> Module Name -> Paths -> Test output path
You need to set up the Scala SDK.
1.) Usually, intelliJ will ask you by showing a message on right hand corner of your editor
2.) You can do it by yourself as mentioned on the https://www.jetbrains.com/help/idea/discover-intellij-idea-for-scala.html
In my case, I was missing the Scala facet in my module.
https://blog.jetbrains.com/scala/2010/09/02/project-configuration-explained/
I got rid of the error once I configured module properly.
You can try to recompile the test classes:
sbt test:compile
If you are using IntelliJ to run scalatest make sure the class paths are correct. For example:
/dummyApp
your build.sbt should look like, name := "dummyApp". If you name it name := "dummy App" you will get errors.
In my case I had in Preferences -> Build, Execution, Deployment -> sbt
Use sbt shell for build and import checkbox enabled
And the test was not in the expected directory src/test but in src/it (integrated test).
I encountered the error when the test class was not part of any package.
I am using the multi maven module and tried all possibilities here but not able to fix this. But for me I closed the complete IntelliJ -> removed .idea folder -> deleted managed projects from recent projects window.-> reimport the project did the job.
This kind of thing keeps happening to me every now and then. All the more concrete suggestions above have merit. Another possibility (which worked this time for me): Edit the run configuration for your tests; click "Use sbt"; run the tests (this should have no problem since it's just using the sbt-shell to run the tests); now unselect "Use sbt" and try it. It worked for me.
Another one in the long list of checks, if you do not use unique test names you get this error without any hint, in a long test suite it is easier to miss.
Failed
test("Check thing 1") {
class TestClass1 extends MainClass1{
... }
test("Check thing 1") {
class TestClass2 extends MainClass2{
... }
Successful
test("Check thing 1") {
class TestClass1 extends MainClass1{
... }
test("Check thing 2") {
class TestClass2 extends MainClass2{
... }
I got the same message on Idea 2021.1. I tried all the ways above but what helped me is running Scala-tests via sbt like this:
sbt "; project nameOfProject; testOnly some.package.SomeTest"
After that I could debug the same tests via Idea.
I had two modules marked as Test Sources Root and thus it didn't like that. So I unmarked one and then it worked great