I have configuration class:
@ConfigurationProperties(prefix = "myConfig")
public class MyConfig {
protected String config;
}
My service uses this config class (That gets the value from application.yml
):
@Service
public class myService {
@Inject
private MyConfig myConfig;
Public String getInfo (String param) {
if (isEmpty(param)) { throw new InvalidParameterException; }
return myConfig.getConfig();
}
}
I'm trying to test it with Mockito:
@RunWith(MockitoJUnitRunner.class)
public class myTest {
@InjectMocks
private MyService myService;
@Mock
private MyConfig myConfig;
@Test
public void myTest1() {
myService.getInfo("a");
}
@Test
public void myTest2() {
assertThrows(InvalidParameterException.class, ()->myService.getInfo(null));
}
}
myTest
fails since the config class is mocked, thus has null values.
What is the right way to test configuration class with Mockito?
Edit:
I have a number of config classes like the one above that are being used in myService
.
You need to create getter which then can be mocked by Mockito.
@ConfigurationProperties(prefix = "myConfig")
public class MyConfig {
protected String config;
public String getConfig() {
return config;
}
}
.
@RunWith(MockitoJUnitRunner.class)
public class myTest {
@InjectMocks
private MyService myService;
@Mock
private MyConfig myConfig;
@Before
private void initializeConfig() {
when(myConfig.getConfig()).thenReturn("someValue");
}
@Test
public void myTest1() {
myService.getInfo("a");
}
}
But if you don't want to set the value explicitly in test, you should create a Spring integration test which would create the whole context and use the real objects. But this is out of scope of this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With