From b3c31725b779d0287fff79728227556751f837f2 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20=E2=80=98Bombe=E2=80=99=20Roden?= Date: Sat, 23 Jul 2022 23:24:13 +0200 Subject: [PATCH] =?utf8?q?=E2=9C=85=20Add=20JUnit=20Rule=20to=20override?= =?utf8?q?=20locales=20during=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Some tests fail when run with a non-English locale. This was found by debbiedub (see https://github.com/Bombe/Sone/pull/23) but their proposed solution was not quite to my liking. This TestRule will store the JVM’s current default locale and set a custom locale before running a test. After the test the previous locale will be restored, in order not to mess up any other tests. --- .../net/pterodactylus/sone/test/OverrideLocale.kt | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 src/test/kotlin/net/pterodactylus/sone/test/OverrideLocale.kt diff --git a/src/test/kotlin/net/pterodactylus/sone/test/OverrideLocale.kt b/src/test/kotlin/net/pterodactylus/sone/test/OverrideLocale.kt new file mode 100644 index 0000000..c4b4b0d --- /dev/null +++ b/src/test/kotlin/net/pterodactylus/sone/test/OverrideLocale.kt @@ -0,0 +1,24 @@ +package net.pterodactylus.sone.test + +import org.junit.rules.ExternalResource +import java.util.Locale + +/** + * JUnit [test rule][org.junit.rules.TestRule] that overrides the + * [JVM’s default locale][Locale.getDefault] for the duration of a test, + * restoring it to its previous value after the test. + */ +class OverrideLocale(private val locale: Locale) : ExternalResource() { + + override fun before() { + previousLocale = Locale.getDefault() + Locale.setDefault(locale) + } + + override fun after() { + Locale.setDefault(previousLocale) + } + + private var previousLocale: Locale? = null + +} -- 2.7.4