测试使用project.gradle.projectsEvaluated的Gradle插件

时间:2018-03-02 13:49:44

标签: unit-testing gradle-plugin

我正在尝试测试使用BuildAdapter#ProjectsEvaluated函数的Gradle插件,以允许将自定义配置和依赖项添加到我的项目中。我遇到的问题是,如果我在junit测试中使用InternalProject#evaluate评估项目,那么projectEvaluated函数永远不会被调用。如果我切换到更健壮的GradleRunner,那么我似乎没有能力稍后检查项目以实际查看我的插件是否有效。我在下面提供了示例代码,其中显示了一个示例插件和一个junit测试。有谁知道我如何测试这个功能?

class MyPlugin implements Plugin<Project> {
  @Override
  void apply(Project project) {           
    project.extensions.create("myPlugin", MyPluginExtension)
    project.gradle.projectsEvaluated {
       /*
           custom logic that needs to evaluate prior 
           to gradle adding dependencies to project
       */
    }
}

JUnit如下:

class MyPluginPluginTest {

  private Project project

  @Before
  void setup() {
    project = ProjectBuilder.builder().build()
    project.repositories.mavenCentral()
    project.apply plugin: 'java'
    project.apply plugin: MyPlugin
  }

  /*
    Test to check whether or not the correct dependency 
    was added to the project when the plugin was evaluated
  */
  @Test 
  void projectHasCheckerFrameworkDependencies() {
     ((ProjectInternal) project).evaluate()

     Set<File> files = project.configurations.getByName('myPlugin').resolve()
     assertNotEquals(0, files.size())
     assertTrue(files.any { it.name.endsWith("myDependency-${project.jarName.version}.jar") })
  }
}

1 个答案:

答案 0 :(得分:0)

为了获取我所需的信息,我将projectsEvaluated闭包添加到projectExtensions中,如下所示:

class MyPlugin implements Plugin<Project> {
  @Override
  void apply(Project project) {           
    project.extensions.create("myPlugin", MyPluginExtension)
    def projectsEvaluatedClosure = {
      /*
         custom logic that needs to evaluate prior 
         to gradle adding dependencies to project
      */
    }

    project.extensions.add("myPluginProjectsEvaluatedClosure", projectsEvaluatedClosure)
    project.gradle.projectsEvaluated closure
  }
}

现在项目中可以访问projectsEvaluated闭包,我从测试用例中手动执行了闭包。这不是一个理想的解决方案,但我能够验证代码是否正常工作。