Having two Projects:
Classic (Having main class)
Advanced
Id like to have the Advanced to have all classes the Classic have. But as I run Advanced/gradle bootRun all the Advanced classes seems to be missing.
Advanced/src/main/java/foo/Bar.java:
package foo;
public class Bar{
//empty
}
Classic/src/main/java/foo/Classic.java:
package foo;
public class Classic {
public static void main(){
try {
Class.forName("foo.Bar");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Exception:
java.lang.ClassNotFoundException: foo.Bar
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:340)
at foo.Classic.main(Classic.java:14)
java.lang.ClassNotFoundException: foo.Bar
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at org.springframework.boot.devtools.restart.classloader.RestartClassLoader.loadClass(RestartClassLoader.java:144)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:340)
at foo.Classic.main(Classic.java:14)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
I have this in my Advanced/build.gradle:
...
dependencies{
...
implementation project(':classic')
...
}
...
Important info from Comments:
Jacob G.
I talked for awhile with OP in one of the chat rooms, and I've discovered a few things. When attempting to build the Advanced project with Gradle, it reports 50+ compilations errors regarding package not found:, referring to packages in the Classic project. Also, Classic and Advanced do not share a root project, so I have a feeling that attempting to depend on project(':classic') is futile. OP stated that commits can only be made to Advanced, so it may not be possible to fix the issue at all. For anyone curious, OP is also not using an IDE.
Statement of respect
I made an edit to the question, I added an limitation. It was an very important edit that I can only commit changes in Advanced. Because of the fact that I have no experience in gradle I was not aware of the imporance of this additional information. I feel sorry for the late limitation, feel comfort for the courtesy and hope for understanding.
As far as I could understand from the question we are dealing with a multiple project scenario. In this case the multi project builds documentation tells us that it is necessary to have a settings.gradle in the folder that contains the two projects:
then it is possible to run both the projects without cd change directory into the specific folder , but directly from the multi-project root by command: gradle advanced:bootRun
EDIT according to 20200610 EDIT of the question acknowledging the specification: commits can only be made to the Advanced project.
we can still get a solution but in this scenario ( actually not a gradle multi-project)
no need to have a settings.gradle at the parent directory level of Advanced; it satisfy the requirement of not being able to commit outside of Advanced
it doesn't matter how it's built the Classic project, we don't care about it since we can't commit on it
we can't use in Advanced/build.gradle the implementation project(':classic') as dependency since this works only in real gradle multi-project scenarios ; in here we must use a file dependency or another type of dependecy available for the user's development environment.
In this case it is possible to run the Advanced project by cd Advanced then , from the Advanced directory run th command: gradle bootRun
why it works ?
..In order to better understand how it works lets's inspect the
SystemClassLoader's current paths by adding this lines of code in Advanced/src/main/java/com/example/springboot/Application.java
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
the output is:
<multi-project-root>/Advanced/build/classes/java/main/
<multi-project-root>/Advanced/build/resources/main/
<multi-project-root>/Classic/build/libs/Classic-0.0.1-SNAPSHOT.jar
~/.gradle/caches/modules-2/files-2.1/org.springframework.boot/spring
... [suppressed many othe spring devtools and gradle related caches ]
this allow both the Advanced and the Classic classes to find each others
source code of a proof of concempt
The POC source-code new branch has been updated accordingly
What you need is Gradle's composite build. See my POC project.
The advanced project includes the classic project by this line
The advanced/App.java calls classic.App.main, And the classic.App class can load foo.Bar from the advanced project. No need to do a commit to classic project.
Execute "gradlew run" in the advanced folder
to see how it works.
I also had the same project structure as the one you have so by making below-mentioned changes it works fine for me :
Entry in build.gradle file
compile project(':Classic')
Entry in settings.gradle
include ':Classic'
project(':Classic').projectDir = new File(settingsDir, '../../libs/Classic')
I hope this will work for you too and yes don't forget to rebuild your grade project after making these changes.
I am trying to do my first test-automation with Spock.
I do not want to use maven.
I am using eclipse java EE oxygen 4.7.
I have created a groovy project.
I have added the Spock jar as an external library in the build path configuration.
Spock ist Spock-core-1.1-groovy-2.4.
I have also added geb jar the same way.
However, I am getting this strange error from the automatic build, which I do not understand and I am seeking for help. So far I haven't found anything helpfull.
General error during semantic analysis: Transform org.spockframework.compiler.SpockTransform#xxxx cannot be run org.codehaus.groovy.GroovyException:
Transform org.spockframework.compiler.SpockTransform#xxxx cannot be run at
org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:416) at
org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:972) at
org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:633) at
org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:609) at
org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:586) at
org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.processToPhase(GroovyCompilationUnitDeclaration.java:217) at
org.codehaus.jdt.groovy.internal.compiler.ast.GroovyCompilationUnitDeclaration.resolve(GroovyCompilationUnitDeclaration.java:613) at
org.eclipse.jdt.internal.compiler.Compiler.process(Compiler.java:879) at org.eclipse.jdt.internal.compiler.ProcessTaskManager.run(ProcessTaskManager.java:141) at
java.lang.Thread.run(Unknown Source) Caused by: java.lang.NoClassDefFoundError: Unable to load class org.spockframework.runtime.ErrorCollector due to
missing dependency org/junit/runners/model/MultipleFailureException at org.codehaus.groovy.vmplugin.v5.Java5.configureClassNode(Java5.java:397) at
org.codehaus.groovy.ast.ClassNode.lazyClassInit(ClassNode.java:353) at org.codehaus.groovy.ast.ClassNode.getDeclaredMethods(ClassNode.java:981) at
org.codehaus.groovy.ast.ImmutableClassNode.getDeclaredMethods(ImmutableClassNode.java:105) at
org.spockframework.compiler.AstNodeCache.(AstNodeCache.java:65) at org.spockframework.compiler.SpockTransform$Impl.(SpockTransform.java:
52) at org.spockframework.compiler.SpockTransform.visit(SpockTransform.java:47) at
org.codehaus.groovy.transform.ASTTransformationVisitor$3.call(ASTTransformationVisitor.java:395) ... 9 more
My code is as simple as you can get. This is the code:
//The error is on the "p" letter of package
package hellowworld
class HelloWorld{
static main(args) {
}
}
Please note that this error only happens when I add Spock jar. The closest question was Spock without maven or gradle, but obviously the problems are different.
I just cut the file from the package directory pasted it out side and then recut pasted in the package back. It worked well and I have no idea why.
This is one of those problems which occasionally arise in Eclipse and most people just won't know why!
The thing to do usually is to try several "strategies" and hope that one will work. If not you have to come back to SO and try to enlist the support of an expert.
One tip: in my experience sometimes it is worth trying "Refresh Gradle" and "Build all" more than once. Not only that, but sometimes trying either of these actually then seems to do nothing... but a couple of seconds later the horrid x in the red box then vanishes like morning mist!
Highlight/select the project in Project Explorer --> right-click --> Gradle --> Refresh Gradle Project
Put cursor in a code file open in the editor, press Ctrl-B (Project --> Build all)
Close all files in editor, close Eclipse and start up Eclipse again
Try the above in various combinations
Reboot and then try the above in various combinations
If this fails to cure it you may need to turn to SO.
I am building an application using Gradle, JDK 8, Java FX, and Test FX. I need to be on JDK 8 for our application to work on all platforms with our tech stack. My problem is that I am unable to get code coverage into our build. I found this link...
https://github.com/jacoco/jacoco/issues/74
...and using the Jacoco preview build at the top, I was able to replace my intellij JARs and successfully run my tests and get the coverage. However, I am having trouble putting this into my build.gradle. From what I can tell, I need to add a local repository in my build script...
...
apply plugin: "jacoco"
...
buildscript {
repositories {
// Local Repo
// MVN Repo(s)
}
dependencies {
// Classpaths
}
}
jacoco {
toolVersion = "0.6.4.201311160552" // I need this specific version, which isn't on a MVN repo
}
...I tried to add my local repo several ways including...
flatDir(dirs: "lib")
flatDir dirs: "${projectDir}/lib"
maven { url uri("lib") }
one or two other ways I forget
...my lib folder contains the exact contents, unchanged, from the preview build zip's lib folder in the link above. It doesn't seem like gradle is having a problem locating the local repo, but it is having trouble finding the JAR. I assume there is something wrong with the way I am naming it or the way that it is "packaged". I have tried modifying the JAR names but I keep getting the error...
What went wrong:
A problem occurred configuring root project 'myProject'.
Could not resolve all dependencies for configuration ':classpath'.
Could not find :org.jacoco.agent:.
Required by:
:myProject:unspecified
...any ideas why my JAR is not being found? Thanks!
"Answering" my own question, despite the fact that I still haven't quite figured it out. Anyways, here are two links I found that seem to solve my problem...
http://forums.gradle.org/gradle/topics/jacocotestreport_is_skipping
...following some of these instructions allow my tests to run, but I am still not able to run "gradle jacocoTestReport" without it failing.
UPDATE
OKAY! I figured it out, the link above did help me figure it out. My problem was with the asm-all JAR, since there were several, I did not know which one to use. In order to get jacoco working with Java 1.8, you do not need to specify the toolVersion property. All you need to do is add the following to your dependencies block (not the buildscript block, the code block)...
jacocoAgent files(
"$projectDir/lib/org.jacoco.agent-0.6.4.201311160552.jar")
jacocoAnt files(
"$projectDir/lib/org.jacoco.ant-0.6.4.201311160552.jar",
"$projectDir/lib/org.jacoco.core-0.6.4.201311160552.jar",
"$projectDir/lib/org.jacoco.report-0.6.4.201311160552.jar",
"$projectDir/lib/asm-all-5.0_BETA.jar")
...where the asm-all-5.0_BETA.jar is taken from the org.ow2.asm group found at...
http://mvnrepository.com/artifact/org.ow2.asm/asm-all/5.0_BETA
...hope this helps!
for reference, latest jacoco libs are changed so i'm sharing the following snippet:
dependencies{
jacocoAgent files("$rootProject.projectDir/lib/org.jacoco.agent-0.8.3.201904130250.jar")
jacocoAnt files("$rootProject.projectDir/lib/org.jacoco.ant-0.8.3.201904130250.jar",
"$rootProject.projectDir/lib/org.jacoco.core-0.8.3.201904130250.jar",
"$rootProject.projectDir/lib/org.jacoco.report-0.8.3.201904130250.jar",
"$rootProject.projectDir/lib/asm-7.0.jar",
"$rootProject.projectDir/lib/asm-tree-7.0.jar",
"$rootProject.projectDir/lib/asm-commons-7.0.jar"
)
}
I have done more than an hour of searching while trying to run JUnit on my project. I can see that there is a class missing - LogEntryFormatter. But no matter how hard I tried, I am not able to find the jar file which contains this one. Eclipse shows the below stack trace after running the Test case file.
java.lang.NoClassDefFoundError: weblogic/logging/LogEntryFormatter
at java.lang.ClassLoader.findBootstrapClass(Native Method)
at java.lang.ClassLoader.findBootstrapClass0(ClassLoader.java:892)
at java.lang.ClassLoader.loadClass(ClassLoader.java:302)
at java.lang.ClassLoader.loadClass(ClassLoader.java:300)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at weblogic.logging.commons.LogImpl.(LogImpl.java:14)
at weblogic.logging.commons.LogFactoryImpl.getInstance(LogFactoryImpl.java:21)
at weblogic.logging.commons.LogFactoryImpl.getInstance(LogFactoryImpl.java:18)
at org.apache.commons.logging.LogFactory.getLog(LogFactory.java:685)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.(SpringJUnit4ClassRunner.java:91)
...
When I use #RunWith(SpringJUnit4ClassRunner.class) and if I use #RunWith(JUnit4.class), a sample test seems to work.
Any sort of help will be useful. I am using WebLogic server, and all weblogic related jars are available on the classpath.
Ok, so after a lot of effort I am able to run JUnit Tests, although not in the exact way I want. I am also at a loss to explain why this is happening or where weblogic.logging is configured. This could be a possible problem with my project setup. After adding the following jar files to the classpath (after removing everything except jdk), it seems to be working for me.
wlclient
com.bea.core.utils.classloaders
com.bea.core.descriptor
com.bea.core.utils
com.bea.core.management.core
junit 4.5
Thanks to all those who helped by providing valuable comments. The stack traces encountered at each step helped me point in the right direction.
When I attempt to run the following test in IntelliJ IDEA I get the message:
"!!! JUnit version 3.8 or later expected:"
It should be noted that this is an Android project I am working on in IntelliJ IDEA 9.
public class GameScoreUtilTest {
#Test
public void testCalculateResults() throws Exception {
final Game game = new Game();
final Player player1 = new Player();
{
final PlayedHole playedHole = new PlayedHole();
playedHole.setScore(1);
game.getHoleScoreMap().put(player1, playedHole);
}
{
final PlayedHole playedHole = new PlayedHole();
playedHole.setScore(3);
game.getHoleScoreMap().put(player1, playedHole);
}
final GameResults gameResults = GameScoreUtil.calculateResults(game);
assertEquals(4, gameResults.getScore());
}
}
The full stack trace looks like this...
!!! JUnit version 3.8 or later expected:
java.lang.RuntimeException: Stub!
at junit.runner.BaseTestRunner.<init>(BaseTestRunner.java:5)
at junit.textui.TestRunner.<init>(TestRunner.java:54)
at junit.textui.TestRunner.<init>(TestRunner.java:48)
at junit.textui.TestRunner.<init>(TestRunner.java:41)
at com.intellij.rt.execution.junit.JUnitStarter.junitVersionChecks(JUnitStarter.java:152)
at com.intellij.rt.execution.junit.JUnitStarter.canWorkWithJUnitVersion(JUnitStarter.java:136)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:110)
Process finished with exit code -3
This problem happens because Android Platform (android.jar) already contains JUnit classes. IDEA test runner loads these classes and sees that they are from the old JUnit, while you are trying to use annotated tests which is a feature of the new JUnit, therefore you get the error from the test runner.
The solution is simple, open the Project Structure | Modules | Dependencies, and move the junit-4.7.jar up, so that it comes before Android 1.6 Platform in the classpath. Now the test runner will be happy as it loads the new JUnit version.
my module is a java library module, so changing JRE to 1.8 java solved the issue.
Or, you can also do it globally via Module Settings > SDK Location > JDK, specifying Oracle's JDK 8 instead of Android SDK's copy.
I had this problem with a multi module project (libgdx). One module is pure Java and has tests.
My solution was to set "use alternative JRE" to "Java 1.8" in the run configuration of my unit tests. This makes sure no android.jar is on the classpath and the junit 4.x runner is used.
I got the same error when creating both Unit Test and Android Instrument Test in Android Studio 1.4+ and it started to get confused. To avoid this error make sure your test class is fall under Android Tests on Run/Debug Configurations
Make sure you follow the instruction properly https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html
Make sure Test Artifact in Build Variants is set to Android Instrumentation Tests
Click menu Run > Edit Configuration
Make sure your class/method name is inside Android Tests instead of JUnit
If it is in JUnit simply delete the config and right click on the file you want to test and Run again. It will then create the config under Android Tests section and it run on device/emulator.
For Android Studio - starting from Android Studio 1.1 Beta 4, Google has added support for Android Gradle plugin 1.1.0-RC. The new plugin supports Unit Testing through Android Studio using junit 4+.
This is still experimental and there are some manual steps to set this up.
For everyone who is reading this post and still have the same issue with AndroidStudio 1.0. You cannot change the dependency order in AndroidStudio has the IDE re-write them automatically. And, even if you manage to change the order by modifying the .iml file, you will get a "class not found...". This is because the Test output path cannot be set on AndroidStudio.
Actually, there is solution to make AndroidStudio, Junit and Robolectric working together. Take a look at this https://github.com/JCAndKSolutions/android-unit-test and use this plugin as well : https://github.com/evant/android-studio-unit-test-plugin
Works perfectly for me.
For me this problem was caused by an outdated/broken run configuration for the tests. I simply had to delete the configuration, then create a new one and the problem was fixed.
I have got the same error when i have create my own junit package
To fix this, i have added these two lines in my app gradle file as it's explained here :
dependencies {
...
// Required -- JUnit 4 framework
testCompile 'junit:junit:4.12'
// Optional -- Mockito framework
testCompile 'org.mockito:mockito-core:1.10.19'
}
I got the same message
JUnit version 3.8 or later expected
by a simple beginner's mistake. I had used the same package names and class names on src/main and src/test for a class (the HomeController class in my case):
my-test-project
+--pom.xml
+--src
+--main
+--com
+--example
+--Application.java
+--controller
+--HomeController.java
+--test
+--com
+--example
+--ApplicationTest.java
+--controller
+--HomeController.java <---- same package and class name: not good!
With that, the src/main HomeController class, as well as the src/test HomeController class, had the same full path:
com.example.controller.HomeController.class
The result: any tests that were dependent on the HomeController class have failed.
Either changing the package name and/or the class name has resolved the issue. Here the example, when both, the package name and the class name is changed:
my-test-project
+--pom.xml
+--src
+--main
+--com
+--example
+--Application.java
+--controller
+--HomeController.java
+--test
+--com
+--example
+--test <---- added (optional)
+--ApplicationTest.java
+--controller
+--HomeControllerTest.java <---- changed
Now the fully qualified class names differ. The src/main HomeController class name is:
com.example.controller.HomeController.class
and the src/test HomeHontrollerTest class name is:
com.example.test.controller.HomeControllerTest.class
With the fully qualified class names being unique, the problem disappears.
There are two thing I could imagine to happen
If your IDE tries to start an Android
Junit test that directly runs on the
emulator you can't use Junit4.
If you accidentally used the junit classes provided from the android jar they can't run on a normal jvm because there are only real compiled classes for the android dalvik vm.
This happened to me as well in Android Studio 1.1 - although it should support unit tests without a plugin.
On other machines (same project, same version of AS) I found that when running unit tests, the IDE does not add the android.jar file to the classpath, while in my machine it does.
My best guess was that due to the conversion we did from Maven to Gradle and moving from intellij to AS some cache of settings remained somewhere in my machine that caused android.jar to be added to the classpath.
What I did is to clear all android related caches from my machine (under the c:\users\USRE_NAME folder):
.android
.AndroidStudio
.gradle
.m2
After that I reopened the project and the tests worked.
Still trying to understand what went wrong, but this should do the trick for now.
I had this issue in Android Studio 1.5, because I did not know that I had to switch the "Test Artifact" setting in the "Build Variants" (lower left corner of the main window) from "Android Instrumentation Tests" to "Unit Tests". When you do, you can see an ExampleUnitTest.java file in the Project window.
I had the same problem but for another reason. I was on IntelliJ with a regular java gradle project (not android) but the JDK was set to the Android SDK in Project Structure (was the default JDK for some reasons). This is really dumb but IntelliJ wasn't nice enough to indicate me what's wrong, so I got stuck on that.
This is how I solved it:
Edit Configurations -> Defaults -> Android JUnit -> Add the following to Working Directory:
$MODULE_DIR$
Worked when I update IDEA version to 2021.2.1.
In Android project I had minifyEnabled = true, after I changed it to false everything worked.
If you remove
testOptions {
unitTests.returnDefaultValues = true
}
from your build.gradle it will work
Go to Project Structure -> Platform Setting, change SDKs to 1.8
solved my problem.
I followed CrazyCoder's answer but there was no junit file shown in dependencies. so i downloaded one from http://www.java2s.com/Code/Jar/j/Downloadjunitjar.htm, then added it by pressing the plus button on the right. And it worked
Turning off "Use embedded JDK" in Project Structure/SDK Location is what helped in my case but I don't know exactly what was the reason it was failing in the first place.
Replace your android.jar in libs folder with the latest one.
You can download it from here
In AndroidStudio, Open Project Structure -> SDK Location, you can see JDK location, change use "Use embedded JDK" to you own JDK to apply, then change back to "Use embedded JDK", it's maybe work
In my case, change JRE in Run Configurations dose solve the problem, but when I click the run button next to the test function, the JRE options will reset to default.
Finally, similar to #CrazyLiu 's answer, in Project Structure - SDK Location - JDK, select Embedded JDK. Because there is no checkbox in Android Studio 3.6.
None of the above worked for me (Intellij 2019.3.5
Build #IU-193.7288.26), finally using 're-import all projects' button on the maven pane worked.
For me, i did delete useLibrary 'android.test.runner' line in android {} block at bulid.gradle module file and everything worked fine.
I had the same problem in a Java 11 with Spring project, turns out when I tried to run the test, I put the wrong "shorten command" option.
Using the "JAR Manifest" option fixed the issue.
IntelliJ shorten command options
I was also facing the same issue, after changing into build.gradle it's working fine for me.
change your junit version inside build.gradle to:
testImplementation 'junit:junit:3.8'