How to mock ResourceBundle.getString()?

前端 未结 4 1054
盖世英雄少女心
盖世英雄少女心 2021-02-19 03:35

I\'m failing to mock ResourceBundle.getString().

This is my code:

ResourceBundle schemaBundle = Mockito.mock(ResourceBundle.class);
Mockito.         


        
4条回答
  •  太阳男子
    2021-02-19 03:55

    Instead of mocking you can create a dummy ResourceBundle implementation, and then pass it in .thenReturn(resourceBundle):

        import java.util.ResourceBundle;
    
        ResourceBundle dummyResourceBundle = new ResourceBundle() {
            @Override
            protected Object handleGetObject(String key) {
                return "fake_translated_value";
            }
    
            @Override
            public Enumeration getKeys() {
                return Collections.emptyEnumeration();
            }
        };
    
        // Example usage
        when(request.getResourceBundle(any(Locale.class))).thenReturn(dummyResourceBundle)
    

    If you need the actual keys and values, then you'll need to provide an implementation for getKeys(), e.g. a hashmap for storage and key lookup.

提交回复
热议问题