0
public class CacheAdder{

private static final int HARD_CACHE;

static {
    HARD_CACHE = 22;
    try {
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
  public int divide(int number, int divider) {
         return  (int) HARD_CACHE+number/divider;
    }
}

When I mock and run tests through this example class, mockito skips the static part which makes sense because I mock the value of HARD_CACHE but at the same time I want 100% coverage through the code. Should static fields be tested without mocks? Or is there a way to test static fields/methods/variables using mocks?

Jeredriq Demas
  • 616
  • 1
  • 9
  • 36

1 Answers1

0

One way to do it is to use reflection for setting the value to the static field

You can look here: Mock private static final field using mockito or Jmockit

  • Yes but I'm asking about a field, this is a class called Logger which can be mocked without any problem. In other words what I'm asking is mocking HARD_CACHE but also waiting 3 seconds – Jeredriq Demas Jun 16 '20 at 07:34
  • Check how you initialize mocks, otherwise, try to use spy instead. https://stackoverflow.com/questions/43577079/use-static-initialization-block-with-mockito – Daimon Cool Jun 16 '20 at 07:40