Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing @ConfigurationProperties with Mockito

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.

like image 384
John Ellis Avatar asked Sep 19 '25 20:09

John Ellis


1 Answers

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.

like image 57
mwajcht Avatar answered Sep 21 '25 15:09

mwajcht