Created
September 2, 2025 19:52
-
-
Save josinovmota/443f8fcb4c3860ed23fb5f549e272072 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.nemesis.training; | |
import org.junit.jupiter.api.Test; | |
import java.util.Properties; | |
import static org.junit.jupiter.api.Assertions.*; | |
class ConfigLoaderTest { | |
@Test | |
void mustLoadApplicationPropertiesWhenFileExists() { | |
// Arrange | |
String fileName = "application.properties"; | |
// Act | |
Properties props = ConfigLoader.load(fileName); | |
// Assert | |
assertFalse(props.isEmpty()); | |
} | |
@Test | |
void mustThrowIllegalArgumentExceptionWhenFileDoesNotExist() { | |
// Arrange | |
String fileName = "foo.properties"; | |
// Act + Assert | |
assertThrows(IllegalArgumentException.class, () -> ConfigLoader.load(fileName)); | |
} | |
@Test | |
void mustThrowIllegalStateExceptionWhenFileIsEmpty() { | |
// Arrange | |
String fileName = "empty.properties"; | |
// Act + Assert | |
assertThrows(IllegalStateException.class, () -> ConfigLoader.load(fileName)); | |
} | |
@Test | |
void mustGetPropertiesFromApplicationPropertiesWhenGetPropertyIsCalled() { | |
// Arrange | |
System.setProperty("config.file", "application.properties"); | |
// Act | |
Properties props = ConfigLoader.loadSystemPropertyAndLoad(); | |
// Arrange | |
assertNotNull(props); | |
} | |
} | |
---------------------------------------------------------------------------------------------------------------------------------- | |
package com.nemesis.training; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.UncheckedIOException; | |
import java.util.Properties; | |
public class ConfigLoader { | |
public static Properties load(String fileName) { | |
Properties props = new Properties(); | |
try (InputStream input = ConfigLoader.class.getClassLoader().getResourceAsStream(fileName)) { | |
if (input == null) { | |
throw new IllegalArgumentException("ERROR: File not found: " + fileName); | |
} | |
props.load(input); | |
if(props.isEmpty()) { | |
throw new IllegalStateException("ERROR: Properties file is empty: " + fileName); | |
} | |
} catch (IOException e) { | |
throw new UncheckedIOException("ERROR: Error while loading: " + fileName, e); | |
} | |
return props; | |
} | |
public static Properties loadSystemPropertyAndLoad() { | |
return load(System.getProperty("config.file", "application.properties")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment