package de.rwu.easydrop.util; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.fail; import java.util.NoSuchElementException; import javax.naming.ConfigurationException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ConfigImplTest { private Config config; private final static String TESTDATA_PATH = "src/test/resources/testdata.properties"; private final static String TESTDATA_KEY = "API_KEY"; private final static String TESTDATA_VAL = "keyIsHere"; @BeforeEach void setUp() { config = Config.getInstance(); } @Test void testGetProperty_ExistingKey() throws ConfigurationException { config.setConfigLocation(TESTDATA_PATH); config.loadConfig(); config.setProperty(TESTDATA_KEY, TESTDATA_VAL); String value = config.getProperty(TESTDATA_KEY); assertEquals(TESTDATA_VAL, value); } @Test void testGetProperty_ConfigNotLoaded() throws Exception { config.reset(); NoSuchElementException exception = assertThrows(NoSuchElementException.class, () -> { config.getProperty(TESTDATA_KEY); }); assertEquals("Config has not been loaded", exception.getMessage()); } @Test void testGetProperty_NonExistingKey() { try { config.setConfigLocation(TESTDATA_PATH); config.loadConfig(); NoSuchElementException exception = assertThrows(NoSuchElementException.class, () -> { config.getProperty("I_DONT_EXIST"); }); assertEquals("Requested config value does not exist", exception.getMessage()); } catch (ConfigurationException e) { fail("ConfigurationException should not be thrown"); } } @Test void testSetProperty() { try { config.setConfigLocation(TESTDATA_PATH); config.loadConfig(); config.setProperty(TESTDATA_KEY, "12345"); assertEquals("12345", config.getProperty(TESTDATA_KEY)); } catch (ConfigurationException e) { fail("ConfigurationException should not be thrown"); } } @Test void testLoadConfigSuccessfully() { try { config.setConfigLocation("src/test/resources/testdata.properties"); config.loadConfig(); assertEquals(TESTDATA_VAL, config.getProperty(TESTDATA_KEY)); } catch (ConfigurationException e) { fail("ConfigurationException should not be thrown"); } } @Test void testLoadConfigMissingFile() { config.setConfigLocation("path/that/doesnt/exist/config.properties"); ConfigurationException exception = assertThrows(ConfigurationException.class, () -> { config.loadConfig(); }); assertEquals("Couldn't load required config file", exception.getMessage()); } @Test void testReset() throws ConfigurationException { config.setConfigLocation("src/test/resources/testdata.properties"); config.loadConfig(); assertNotNull(config.getProperty(TESTDATA_KEY)); config.reset(); NoSuchElementException exception = assertThrows(NoSuchElementException.class, () -> { config.getProperty(TESTDATA_KEY); }); assertEquals("Config has not been loaded", exception.getMessage()); } }