'Mock a static field in a Spring JUnit test
I am currently working on a Spring boot project. I'm writing a JUnit 5 test for a class which is as follows,
class TheClassUnderTest {
public String methodToTest() {
Map<Integer, Object> collection = SomeOtherClass.someStaticField;
/*
Some processing logic
*/
}
}
I want to know if there is a way to mock the usage of "SomeOtherClass.someStaticField" so that I can test my class "TheClassUnderTest". I also use Mockito, so any answers using Mockito are also welcome
Solution 1:[1]
Mockito added support for static methods moving since Mockito 3.4.0, and before that you could use powerMockito to achieve this.
Having said that, what you are asking. Mocking static field is not suuportrd by mockito and actually Mockito does not support mocking class fields at all, only methods.
I would suggest wrapping the static variable in some method, and preferably make it non static. Generally avoid static methods, as a class depending on static method of another class is strongly coupled with it and is bad practice for TDD.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Orr Benyamini |
