0

Here is the method I am trying to unit test:

public void setToCache(final String cacheKey, final String value) {
    if (StringUtils.isEmpty(cacheKey)) {
        throw new NamedSystemException(
                ENamedSystemExceptionCode.ILLEGAL_ARGUMENT_EXCEPTION,
                "Cache Key is null or empty.");

    } else if (StringUtils.isEmpty(value)) {
        throw new NamedSystemException(
                ENamedSystemExceptionCode.ILLEGAL_ARGUMENT_EXCEPTION,
                "Value is null or empty.");
    }

    final Jedis jedis = getJedisClient();

    try {
        jedis.set(cacheKey, value);
        jedis.expire(cacheKey, 60);

    } finally {
        jedis.close();
    }
}

How can I mock the Jedis object?

Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
  • 1
    Basically, you can't. You could imagine spying on the object and mock getJedisClient(), but since it's a static method, Mockito can't do anything. To make your code testable, avoid static methods, and use dependency injection to inject your dependencies, rather than looking them up. – JB Nizet May 05 '15 at 08:53
  • @JBNizet I have changed it to an instance method. Should jedis be retrieved from instance as well for it to be mockable? – Oh Chin Boon May 05 '15 at 09:10
  • Yes. Mockito can't mock static methods. – JB Nizet May 05 '15 at 09:16
  • Or you can use PowerMock as described here [Mocking static methods with Mockito][1] [1]: http://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito – Nemanja Maksimovic May 05 '15 at 09:20

1 Answers1

0

Can you describe your getJedisClient() method?

If this method is using an object that is injected in your class (either a direct instance of Jedis or a service proding Jedis), you can easily mock it using

Mockito.mock(yourObject);

It really depends on your getJedisClient() implementation.

Arnaud
  • 36
  • 5