【问题标题】:Testing Custom Gradle Plugins: Providing Configuration Data测试自定义 Gradle 插件:提供配置数据
【发布时间】:2015-01-12 16:54:18
【问题描述】:

我正在尝试测试通过扩展对象配置的自定义 Gradle 插件,该扩展对象通常存在于 build.gradle 文件中。

例如,我的 build.gradle 通常看起来像这样:

{
  apply plugin: 'foobarConfigurator'

  [... stuff ...]

  foobarConfig {
    bar = 'boop'
    baz = 'baap'
    bot = 'faab'
  }

  [... stuff ...]
}

在我的自定义插件类中,我有在 apply 方法中执行此操作的代码:

def config = project.extensions.create('foobarConfig', FooBarConfig)

我不清楚在 JUnit 测试中我应该如何编写测试方法,以便我可以在 ProjectBuilder 类创建的 Project 实例中的 foobarConfiguration 中提供和测试不同的配置值。

任何帮助表示赞赏,谢谢!

【问题讨论】:

    标签: gradle


    【解决方案1】:

    如果您打算为您的扩展编写 JUnit 测试,您可以简单地创建一个实例并以编程方式对其进行配置:

    
    class FooBarConfigTest {
    
        private FooBarConfig fooBarConfig
    
        @Before
        public void before() {
            fooBarConfig = new FooBarConfig()
        }
    
        @Test
        public void example() {
            fooBarConfig.bar = 'boop'
            assertEquals("expectedIfBarIsBoop", fooBarConfig.someMethod())
        }
    
    }
    

    另一方面,要测试插件本身,您可以使用 ProjectBuilder 并按类型查找扩展:

    
    class MyPluginTest {
    
        private MyPlugin plugin
        private Project project
    
        @Before
        public void before() {
            project = ProjectBuilder.builder().build();
            plugin = new MyPlugin()
            plugin.apply(project)
        }
    
        @Test
        public void example() {
            FooBarConfig foobarConfig = project.extensions.findByType(FooBarConfig)
            assertNotNull(foobarConfig)
            foobarConfig.bar = 'boop'
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2011-03-05
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2022-07-31
      相关资源
      最近更新 更多