2
Constants {
    public static final PATH = "/contentFiles";

    // Other constants ...
}

How do I mock the PATH field in my Constants class?

I want to mock the PATH variable to set it to be something along the lines of "/test/contentFiles".

I want my test class to fetch files from a test folder instead of the production "/contentFiles" folder.

Simon Pedersen
  • 43
  • 1
  • 1
  • 8
  • 1
    Why would it be appropriate to mock this? – Louis Wasserman Dec 08 '20 at 21:56
  • @LouisWasserman Does my edit answer your question? – Simon Pedersen Dec 08 '20 at 21:58
  • 1
    In general, you shouldn't structure this as a constants class with static final fields; you should instead structure this as a normal class with instance variables that gets dependency injected into the places you want to use it. That's...really the only way to make this sort of thing practical. – Louis Wasserman Dec 08 '20 at 21:59
  • @LouisWasserman I did consider that, but mocking the constants when testing seems a lot easier and more neat. What's the downside of mocking constants? – Simon Pedersen Dec 08 '20 at 22:01
  • 2
    You may not be able to do it, for starters :) – Louis Wasserman Dec 08 '20 at 22:02
  • @SimonPedersen you should only mock things that are too expensive or otherwise difficult to use the actual value. If you want to be able to inject different values, that's fine, they're just not constants. – Andy Turner Dec 08 '20 at 22:16
  • It just seems overkill to create several files and "boilerplate code" just to be able to stub a single constant for testing. But you are probably right. – Simon Pedersen Dec 08 '20 at 22:18
  • @LouisWasserman What would you name such a class that is to only keep track of the "contentFiles" (input files) path and the "deploymentFiles" (output files) path? – Simon Pedersen Dec 08 '20 at 22:24
  • I wouldn't necessarily create a class, I would inject a `Path` object. – Louis Wasserman Dec 08 '20 at 22:38

1 Answers1

0

If the constant class is not static and you can add a method to your class, add a non-static method that returns the value of your constant and mock that method to return the value you need for testing.

If the constant class is static or can't support non-static methods, you may have to wrap it in a class that does, for example, a ConstantProvider where you can have getters for the constants. Then you can insert a mock for the ConstantProvider and stub the getters as required.

A third approach is to use protected/package-protected non-static global fields in the class under test and set these values directly. This works if the global field is initialized to the constant value outside of the method under test and the test class is in the same package.

Michael McKay
  • 650
  • 4
  • 11