Created
July 29, 2020 18:20
-
-
Save kazusato/a1dd56bbaa0aedfe9dac82176aa6ce77 to your computer and use it in GitHub Desktop.
This file contains 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
# Summary | |
- Enable a "test" profile in the test class. | |
- Check the active profile within the run method of the CommandLineRunner class | |
# MyApplication | |
``` | |
import org.springframework.boot.CommandLineRunner | |
import org.springframework.boot.autoconfigure.SpringBootApplication | |
import org.springframework.boot.runApplication | |
import org.springframework.core.env.Environment | |
@SpringBootApplication | |
class MyApplication(val svc: MyService, val env: Environment) : CommandLineRunner { | |
override fun run(vararg args: String) { | |
if (!env.activeProfiles.contains("test")) { | |
svc.process() | |
} | |
} | |
} | |
fun main(args: Array<String>) { | |
runApplication<MyApplication>(*args) | |
} | |
``` | |
# MyService | |
``` | |
import org.springframework.stereotype.Component | |
@Component | |
class MyService { | |
fun process() { | |
println("Production") | |
} | |
} | |
``` | |
# MyServiceTest | |
``` | |
import org.junit.jupiter.api.Test | |
import org.springframework.beans.factory.annotation.Autowired | |
import org.springframework.boot.test.context.SpringBootTest | |
import org.springframework.test.context.ActiveProfiles | |
@SpringBootTest | |
@ActiveProfiles("test") | |
class MyServiceTest { | |
@Autowired | |
private lateinit var svc: MyService | |
@Test | |
fun testProcess() { | |
svc.process() | |
} | |
} | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment