如何为下面的groovy代码编写测试用例?

tkqqtvp1  于 2023-01-12  发布在  其他
关注(0)|答案(2)|浏览(167)
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")
    }
}

以上Groovy代码的shouldFail和ShouldPass测试用例除外。

wh6knrhe

wh6knrhe1#

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

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'
}
2ledvvac

2ledvvac2#

我试过这个

@Test
void shouldPassWithLocal() {
    def mockEnv = [CREDENTIALS_ID: 'CREDENTIALS_ID']
    stack.env = mockEnv
    def clos = {}
    stack.withLocal(clos)
}

@Test
void shouldFailWithLocal() {
     def mockEnv = [:]
     stack.env = mockEnv
     def clos = {}
     def result = stack.withLocal(clos)
     assertEquals(result, "credentials not setup - env.CREDENTIALS_ID")
 }

但失败情况不是工作错误
java.lang.Exception:未设置凭据-环境凭据ID

相关问题