user9948943
user9948943

Reputation: 9

Gradle Run throwing "Error: Could not find or load main class"

Project Structure is:

src
---main
---test
       ---java
              ---ExecutionClass
                                ---TestNGMain.java

build.gradle is like:

plugins {
    id 'java'
}

apply plugin: 'application'
mainClassName = 'test.java.ExecutionClass.TestNGMain'

jar {
    manifest {
        attributes 'Main-Class': 'test.java.ExecutionClass.TestNGMain'
    }
}

sourceSets {
    test {
        java {
            srcDirs= ['src/test/java']
        }
        resources {
            srcDirs= ['src/test/resources']
        }
    }
}

gradle build - works fine

gradle run - throws error "Couldn't find or Load main class"

Upvotes: 0

Views: 705

Answers (2)

tkruse
tkruse

Reputation: 10685

Running a class from src/test is possible using JavaExec, instead of the application plugin:

task runExample(type: JavaExec, dependsOn: "compileTestJava") {
    classpath = sourceSets.test.runtimeClasspath
    mainClass = "com.example.Example"
}

The purpose of the application plugin is not just to run a class, but to package an application so that it can be deployed, shipped to customers, etc. and it would usually not be desirable to have all the test stuff included at runtime.

So it is a generally bad idea to try to use the application plugin to run anything that is in src/test

Upvotes: 0

Ryotsu
Ryotsu

Reputation: 806

By default the application plugin only considers the main source set as the application code for distribution. If you really want to run code in a test source set, then one option is to include the test sources in the main (bad idea)

sourceSets {
    main{
        java{
            srcDir("src/test/java")
        }
    }
}

The mainClassName = "<package-name>.<class-name>" in your case mainClassName = "ExecutionClass.TestNGMain"

Another way is customize the main distribution to include the test files.

Upvotes: 1

Related Questions