Why does the getter() of mock object return null?

OEurix :

I have a class ResolverChainContext:

public class ResolverChainContext {
  private AWSCredentialsProvider assumeRoleCredentials;
}

and in the setup() in a unit test (Groovy and Spock), I populate the above field with Mock:

def setup() {
  def ctx = ResolverChainContext.builder().build()

  ctx.setAssumeRoleCredentials(Mock(AWSCredentialsProvider.class))
}

Next in my test case, I call a method getDynamoDBCredentialsV2() which I want to get the v1Credentials from getDynamoDBCredentials() which comes from the Mock object in setup() step:


public interface AWSCredentialsProvider {
    AWSCredentials getCredentials();

    void refresh();
}

protected AWSCredentialsProvider getDynamoDBCredentials() {
    final AWSCredentialsProvider fasCredentials = resolverChainContext.getFasCredentials();
    final AWSCredentialsProvider roleCredentials = resolverChainContext.getAssumeRoleCredentials();
    if (null == fasCredentials || !invokerConfig.isUseCallerCredentials()) {
        return roleCredentials;
    } else {
        return fasCredentials;
    }
}

protected AwsCredentialsProvider getDynamoDBCredentialsV2() {

    AWSCredentials v1Credentials = getDynamoDBCredentials().getCredentials();

    blahblahblah;
}

The problem is I will get null for v1Credentials.

When I debug it, the type of roleCredentials is "Mock for type AWSCredentialsProvider". And after calling getCredentials() on it, it gets null.

Is this because I use Groovy in a wrong way? How could I make v1Credentials the object it should be? Should I use Mock/Stub?

ksap :

It returns null since behavior for AWSCredentialsProvider#getCredentials not defined.

From the doc of interaction based testing of Spock, when a behavior is not defined on a mocked object method, its default value will be returned, in your case default value for Object is null

Initially, mock objects have no behavior. Calling methods on them is allowed but has no effect other than returning the default value for the method’s return type (false, 0, or null). An exception are the Object.equals, Object.hashCode, and Object.toString methods

To overcome this you might want to define the behavior for AWSCredentialsProvider#getCredentials method call using stubbing as explained in the doc.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=311107&siteId=1