How to keep Java code and Junit tests together bui

2019-04-06 19:32发布

问题:

I have a project in which the main source and the test cases for that source are kept in the same package/directory. Each test class is the name of the class which it is testing with "Test" appended on the end. So if I have a Foo.java there will be a FooTest.java right next to it.

My question is, how do I build this project with Gradle? I'd still like to keep the class files separate, i.e. a folder for main classes and a folder for test classes.

回答1:

This should do the trick:

sourceSets {
    main {
        java {
            srcDirs = ["some/path"]
            exclude "**/*Test.java"
        }
    }
    test {
        java {
            srcDirs = ["some/path"]
            include "**/*Test.java"
        }
    }
}


回答2:

For reference, here is the code I used to try to get around the Eclipse plugin's classpath issue. Using this in combination with Peter's answer above seems to work.

// The following ensures that Eclipse uses only one src directory
eclipse {
    classpath {
        file {
            //closure executed after .classpath content is loaded from existing file
            //and after gradle build information is merged
            whenMerged { classpath ->
                classpath.entries.removeAll { entry -> entry.kind == 'src'}
                def srcEntry = new org.gradle.plugins.ide.eclipse.model.SourceFolder('src', null)
                srcEntry.dir = file("$projectDir/src")
                classpath.entries.add( srcEntry )
            }
        }
    }
}


回答3:

this work for me:

eclipse {
   classpath {
      file {
        withXml { 
            process(it.asNode())
          }
      }
   }
}
def process(node) {
  if (node.attribute('path') == 'src/test/java' || node.attribute('path') == 'src/test/resources')
    node.attributes().put('output', "build/test-classes")
  else
   node.children().each {
      process(it)
}}


标签: gradle