【问题标题】:how to write an test case for below groovy code?如何为以下常规代码编写测试用例?
【发布时间】:2023-01-10 23:17:59
【问题描述】:
def withLocal(Closure cl) {

    def credentialsId = env.CREDENTIALS_ID

    if (credentialsId) {

        echo("credentials Id=${credentialsId}")

    } else {

        throw new Exception("credentials not setup - env.CREDENTIALS_ID")
    }
}

上面常规代码的 shouldFail 和 ShouldPass 测试用例除外。

【问题讨论】:

    标签: unit-testing groovy


    【解决方案1】:

    根据测试框架的不同,代码可能会略有不同,但我会这样说:

    class A {
      def withLocal(Closure cl) {
        def credentialsId = env.CREDENTIALS_ID
        if (credentialsId) {
            echo("credentials Id=${credentialsId}")
        } else {
            throw new Exception("credentials not setup - env.CREDENTIALS_ID")
        }
      }
    }
    
    // Test
    
    // test 1 should pass: check if echo is called
    // mock env with some value
    A.metaClass.env = [ CREDENTIALS_ID:'abz123' ]
    String out
    // mock echo()
    A.metaClass.echo = { out = it }
    
    A a = new A()
    a.withLocal{}
    assert out == 'credentials Id=abz123'
    
    
    // test 2 should fail: check if exception thrown
    // mock env with empty map
    A.metaClass.env = [:]
    
    a = new A()
    try{
      a.withLocal{}
    }catch( e ){
      assert e.message == 'credentials not setup - env.CREDENTIALS_ID'
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2019-08-19
      • 2019-05-24
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2021-12-08
      相关资源
      最近更新 更多