Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 21 additions & 2 deletions src/main/java/dev/comfast/util/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,36 @@ public static <T> List<List<T>> transposeMatrix(final List<List<T>> matrix) {
* e.g. <pre>{@code
* // here "my.timeout" is 3000
* withSystemProp("my.timeout", () -> {
* System.setProperty("my.timeout", "0");
* doSomeTests();
* System.setProperty("my.timeout", "456");
* //or even System.clearProperty("my.timeout");
* doSomeTestsWith456Timeout();
* })
* // here "my.timeout" is restored to 3000
* }
* @param func within this function can edit system prop freely without side effects for the rest of the code
* }
*/
public static void withSystemProp(String systemPropertyName, Runnable func) {
withSystemProp(systemPropertyName, null, func);
}

/**
* Restore system property after func is done.
* It's safe to edit it inside given function, for test purposes or any other.
* e.g. <pre>{@code
* // here "my.timeout" is 3000
* withSystemProp("my.timeout", "0" () -> {
* doSomeTestsWithZeroTimeout();
* })
* // here "my.timeout" is restored to 3000
* }
* @param func within this function can edit system prop freely without side effects for the rest of the code
* }
*/
public static void withSystemProp(String systemPropertyName, String systemPropertyValue, Runnable func) {
final String restoreValue = getProperty(systemPropertyName);
try {
if(systemPropertyValue != null) System.setProperty(systemPropertyName, systemPropertyValue);
func.run();
} finally {
if(restoreValue == null) clearProperty(systemPropertyName);
Expand Down
21 changes: 14 additions & 7 deletions src/test/java/dev/comfast/util/UtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,25 @@ void transposeMatrixTest() {
@Test
void withSystemPropTest() {
//given
final String KEY = "xx.test", VALUE = "test value";
System.setProperty(KEY, VALUE);
final String KEY = "xx.test",
INITIAL_VALUE = "initial value",
CHANGED_VALUE = "xx is changed";
System.setProperty(KEY, INITIAL_VALUE);

//when
withSystemProp(KEY, () -> System.setProperty(KEY, "changed value"));
//when modify property in func
withSystemProp(KEY, () -> System.setProperty(KEY, CHANGED_VALUE));
assertThat(System.getProperty(KEY))
.isEqualTo(VALUE);
.isEqualTo(INITIAL_VALUE);

//when
//when clear property
withSystemProp(KEY, () -> System.clearProperty(KEY));
assertThat(System.getProperty(KEY))
.isEqualTo(VALUE);
.isEqualTo(INITIAL_VALUE);

//when value passed
withSystemProp(KEY, CHANGED_VALUE, () -> assertThat(System.getProperty(KEY)).isEqualTo(CHANGED_VALUE));
assertThat(System.getProperty(KEY))
.isEqualTo(INITIAL_VALUE);
}

@Test
Expand Down