Home > Net >  how to write an test case for below groovy code?
how to write an test case for below groovy code?

Time:01-11

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")
    }
}

Excepting shouldFail and ShouldPass test cases for above groovy code.

CodePudding user response:

Depending on the test-framework, the code might be slightly different, but I would put it like so:

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

CodePudding user response:

I have tried this

    @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")
 }

But Fail case is not working error

java.lang.Exception: credentials not setup - env.CREDENTIALS_ID

  • Related