diff --git a/lib/src/env.dart b/lib/src/env.dart index d807195..8b219ef 100644 --- a/lib/src/env.dart +++ b/lib/src/env.dart @@ -24,8 +24,8 @@ final class Env { as T; } - if (currentValue == null && defaultValue != null) { - return defaultValue; + if (currentValue == null || currentValue is MissingValue && defaultValue != null) { + return defaultValue as T; } return currentValue as T; diff --git a/test/env_guard_test.dart b/test/env_guard_test.dart index b06bcc6..688ff9e 100644 --- a/test/env_guard_test.dart +++ b/test/env_guard_test.dart @@ -7,12 +7,14 @@ final class Env implements DefineEnvironment { static final String host = 'HOST'; static final String port = 'PORT'; static final String uri = 'URI'; + static final String optionalKey = 'OPTIONAL_KEY'; @override final Map schema = { host: env.string().optional(), port: env.number().integer(), uri: env.string(), + optionalKey: env.string().optional(), }; } @@ -48,7 +50,10 @@ void main() { HOST=localhost '''); - env.define(root: directory, {'PORT': env.number().integer(), 'HOST': env.string()}); + env.define(root: directory, { + 'PORT': env.number().integer(), + 'HOST': env.string(), + }); expect(env.get('PORT'), 8080); expect(env.get('HOST'), 'localhost'); @@ -93,4 +98,14 @@ void main() { test('should get null value when environment has not property', () { expect(env.get('PORT'), isNull); }); + + test('should apply defaultValue when environment has not property', () { + const attemptValue = "Hello World"; + expect(env.get('DONT_EXISTS', defaultValue: attemptValue), attemptValue); + }); + + test('should apply defaultValue when environment has optional property', () { + const attemptValue = "Hello World"; + expect(env.get(Env.optionalKey, defaultValue: attemptValue), attemptValue); + }); }