0

I'm unable to mock the below local objects - env, service, creds. These are classes from imported cloud foundry dependencies.

How do I write a test case covering all conditions for below Groovy code using Spock or Junit 4 without refactoring the code?

import io.pivotal.cfenv.core.cfEnv
import io.pivotal.cfenv.core.cfCredentials
import io.pivotal.cfenv.core.cfService

class Test {
    public String getPropertyValue() {
        CfEnv env = new CfEnv();
        CfService service = new CfService();
        String propName = "test-name";
        try {
            service = env.findServiceByName(propName);
        } catch (Exception e) {
            return null;
        }
        CfCredentials creds = new CfCredentials();
        Map<String, Object> props = service.getMap();
        return props.get("prop.name").toString();
    }
}
Vaishnavi Killekar
  • 457
  • 1
  • 8
  • 22

1 Answers1

0

As your code is Groovy, you are able to use Spock's GroovySpy see the docs

For example:

class ASpec extends Specification {
  def "getPropertyValue() return null when env.findServiceByName throws an exception"() {
  given:
  CfEnv envMock = GroovySpy(global: true)

  when:
  def result = new Test().getPropertyValue()

  then:
  result == null
  1 * envMock.findServiceByName(_) >> { throw new RuntimeException() }
}
Leonard Brünings
  • 12,408
  • 1
  • 46
  • 66