Skip to content

Commit 094ec39

Browse files
[KTLN-571] Getting the Value of a Custom Property Defined in 'gradle.properties' in Kotlin #1077 (#1122)
* code refactor * code refactor
1 parent 7a897f8 commit 094ec39

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

kotlin-build-plugins/build.gradle.kts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,30 @@ dependencies {
1919
detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.0")
2020
testImplementation(kotlin("test"))
2121
}
22+
23+
dependencies {
24+
testImplementation(platform("org.junit:junit-bom:5.9.1"))
25+
testImplementation("org.junit.jupiter:junit-jupiter")
26+
}
27+
28+
tasks.test {
29+
useJUnitPlatform()
30+
}
31+
32+
tasks.withType<Test> {
33+
environment("CUSTOM_PROPERTY", project.findProperty("custom.property") as String)
34+
environment("API_URL", project.findProperty("api.url") as String)
35+
}
36+
37+
tasks.register<Copy>("generateCustomProperties") {
38+
from("${project.rootDir}/gradle.properties")
39+
into("src/generated/resources")
40+
rename { "custom.properties" }
41+
}
42+
43+
tasks.named<Copy>("processResources") {
44+
dependsOn("generateCustomProperties")
45+
from("src/generated/resources") {
46+
include("custom.properties")
47+
}
48+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
api.url=https://api.example.com
2+
custom.property=CustomValue
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.getGradleProperty
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
import java.util.Properties
6+
7+
class GetGradlePropertyValueUnitTest {
8+
9+
@org.junit.jupiter.api.Test
10+
fun `obtain environment variables using System getenv method`() {
11+
val customProperty = System.getenv("CUSTOM_PROPERTY")
12+
val apiUrl = System.getenv("API_URL")
13+
14+
assertEquals("CustomValue", customProperty)
15+
assertEquals("https://api.example.com", apiUrl)
16+
}
17+
18+
@Test
19+
fun `obtain custom property value by loading properties from generated file`() {
20+
val propertiesFileUrl = this::class.java.classLoader.getResource("custom.properties")
21+
?: throw IllegalStateException("Properties file not found")
22+
23+
val properties = Properties().apply {
24+
propertiesFileUrl.openStream().use { load(it) }
25+
}
26+
27+
assertEquals("CustomValue", properties.getProperty("custom.property"))
28+
assertEquals("https://api.example.com", properties.getProperty("api.url"))
29+
}
30+
}

0 commit comments

Comments
 (0)