Testcontainers: execute TC_INITSCRIPT at each test - kotlin

In a quakus project, I successfully set up testcontainers using only the following configuration:
%test.quarkus.datasource.driver=org.testcontainers.jdbc.ContainerDatabaseDriver
%test.quarkus.hibernate-orm.dialect=org.hibernate.dialect.PostgreSQL9Dialect
%test.quarkus.datasource.url=jdbc:tc:postgresql:11:///dbname?TC_INITSCRIPT=file:my-file.sql
This is amazing how easy it is.
However, as I test the deletion of entities, I'd like to execute the initscript before each test, i.a. start each test with the initial DB.
Any idea how to achieve it?
I also tested by creating the PostgreSQLContainer from the test class in order to manage its lifecycle as I need. The problem is that the container port value is random, I need to set it in quarkus configuration but it doesn't work (it seems to be too late: "Connection to 127.0.0.1:6432 refused"). I did it this way:
#Testcontainers
#QuarkusTest
class MyTest {
class MyPostgreSQLContainer(imageName: String) : PostgreSQLContainer<MyPostgreSQLContainer>(imageName)
companion object {
#Container
val postgres = MyPostgreSQLContainer("postgres:11")
.withDatabaseName("integtest")
.withUsername("postgres")
.withPassword("pwd")
.withExposedPorts(5432)
#BeforeAll
#JvmStatic
internal fun beforeAll() {
postgres.start()
System.setProperty("QUARKUS_DATASOURCE_JDBC_URL", "jdbc:postgresql://127.0.0.1:${postgres.firstMappedPort}/kpi_integtest");
println("BeforeAll init() method called")
}
}
with the application.properties config:
quarkus.datasource.jdbc.url=jdbc:postgresql://127.0.0.1:6432/integtest

Related

Kotlin expect generic subclass as parameter

I have an interface which contains a generic and have its extensions working properly, however I'm not able to receive a list of this subclasses as parameter.
The code below works perfectly:
interface Runnable
class FirstRunnable : Runnable
class SecondRunnable : Runnable
interface Runner<in T> where T : Runnable {
fun run(runnable: T)
}
class FirstRunner : Runner<FirstRunnable> {
override fun run(runnable: FirstRunnable) = println("first runner")
}
class SecondRunner : Runner<SecondRunnable> {
override fun run(runnable: SecondRunnable) = println("second runner")
}
The problem comes in the block below:
class ListRunner(private val runners: List<Runner<Runnable>>)
val runner = ListRunner(listOf(FirstRunner(), SecondRunner()))
ListRunner does not accept FirstRunner() and SecondRunner() as parameters and complains with:
Type mismatch.
Required:
List<Runner<Runnable>
Found:
List<Runner<{FirstRunnable & SecondRunnable}>>
I want to inject the list into the ListRunner to be able to run in the entire list at once, within the runner I have a rule to run only accepted Runnable
Solution
Both answers helped me to find out the solution,
As pointed by Nishant Jalan, I had first to add out variance to the ListRunner
class ListRunner(private val runners: List<Runner<out Runnable>>)
And as Sweeper says:
It is not safe to put anything there. The Kotlin type system is smart
enough that it tells you this by saying that run there takes the type
Nothing.
So the solution was adding #UnsafeVariance annotation to the Runner interface:
interface Runner<in T> where T : Runnable {
fun run(runnable: #UnsafeVariance T)
}
Still it is unsafe and the annotation only prevents the compiler to complain about it, however I have a previous verification which guarantee the runnable is run in the correct runner.
You can use a star-projection to say you want a list of any kind of Runner:
class ListRunner(private val runners: List<Runner<*>>)
This will cause the following to compile:
val runner = ListRunner(listOf(FirstRunner(), SecondRunner()))
However, this will also prevent you from running any of the runners in ListRunner. For example, you cannot do this in ListRunner:
fun runAll() {
for (runner in runners) {
runner.run(...)
}
}
Because what actually is the ... part? It is not safe to put anything there. The Kotlin type system is smart enough that it tells you this by saying that run there takes the type Nothing.
You can't pass a FirstRunnable, because runner could be a SecondRunner, which takes a SecondRunnable. You can apply a similar reasoning for why you can't pass a SecondRunnable, or any other Runnable. ListRunner don't know what kind of Runners are in the list, so it can't run it, because different Runners needs different Runnables to run.
Of course, you can check the types of the runner first, then give them the correct kind of runnable:
for (runner in runners) {
when (runner) {
is FirstRunner -> runner.run(FirstRunnable())
is SecondRunner -> runner.run(SecondRunnable())
else -> println("I didn't expect this type of runner!")
}
}
Note that you need an else branch, in case someone passed in a Runner that isn't any of the types you are checking. Anyone can implement your interface, after all!
If you want to eliminate the else branch, you can make Runner sealed:
sealed interface Runner<in T> where T : Runnable {
There are a few things you can tweak in your code to perform the operation that you are looking for.
interface Runner<in T> where T : Runnable can simply be reduced to interface Runner<T : Runnable>. They both do the same thing.
While declaring the ListRunner class, you need to pass a List of Runner of a type that is a Runnable. Hence, you need to replace your type with List<Runner<out Runnable>>
The final code is written below.
interface Runnable
class FirstRunnable : Runnable
class SecondRunnable : Runnable
interface Runner<T : Runnable> {
fun run(runnable: T)
}
class FirstRunner : Runner<FirstRunnable> {
override fun run(runnable: FirstRunnable) = println("first runner")
}
class SecondRunner : Runner<SecondRunnable> {
override fun run(runnable: SecondRunnable) = println("second runner")
}
class ListRunner(private val runners: List<Runner<out Runnable>>)

How to apply a Rule to all test cases in a AndroidJUnitRunner?

I'm trying to apply a TestWatcher as a rule across all my test cases run by a particular runner.
MetadataCollector:
class MetadataCollector : TestWatcher() { ... }
TestRunner:
class TestRunner : AndroidJUnitRunner() {
override fun onCreate(arguments: Bundle?) {
super.onCreate(arguments)
}
override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
return super.newApplication(cl, TestApplication::class.java.name, context)
}
}
All of my test classes currently require MetadataCollector() to be initialized as a Rule:
Test Class:
#JvmField #Rule val collector = MetadataCollector()
Is there a way I can create an instance of this rule automatically to each test case from the runner? Ideally, this is to avoid duplicating this #Rule creation in every single Test Class.
I am unfortunately stuck with JUnit 4 at the moment. :(
There is a better way to do this, by injecting an instance of RunListener into your test runner. In your gradle config, you need to:
defaultConfig.testInstrumentationRunner = "com.mypackage.MyTestRunnerClassName"
defaultConfig.testInstrumentationRunnerArgument("listener", "com.mypackage.MyRunListenerClassName")
And in code, create a RunListenerClassName to implement the corresponding hooks
class MyRunListener : RunListener() {
// impl
}

SpringBootTest with Kotlin, TestContainers and External configuration

I have problem with creating external configuration for my test classes. Right now my redis related tests have to have a companion object inside
#Testcontainers
#TestPropertySource("classpath:/application-test.properties")
#SpringBootTest
class RedisRelatedTest {
companion object {
#Container
val container = GenericContainer<Nothing>("redis:5.0.7-alpine")
.apply { withExposedPorts(6379) }
#JvmStatic
#DynamicPropertySource
fun properties(registry: DynamicPropertyRegistry) {
registry.add("spring.redis.host", container::getHost);
registry.add("spring.redis.port", container::getFirstMappedPort);
}
}
... some tesitng
}
I'd like to move it somewhere outside and and use some one liner to include it but I can't find a way that works. I've created a RedisConfig class with its companion object but #Import(RedisConfig::class) or #Import(RedisConfig.Congig::class) is completely ignored.
#Import(RedisConfig::class) doesn't do anything by itself, you still have to autowire a bean, did you do that as well?
One other option is to have an abstract class with a container and extend it in test classes.
#Import(RedisConfig::class) won't work.
If it is #SpringTest you should rather use:
#SpringBootTest(
classes = [RedisConfig::class])
but I'm not sure if testcontainer annotations will work as you expect. I solved this problem the way I described in this response to similar issue: https://stackoverflow.com/a/66532851/3484423

How to correctly use Mockito's verify on a spring #Service test

I have this service (all in kotlin):
#Service
class MyService {
fun getSomeString(): String = "test"
}
And this integration test class:
#RunWith(SpringRunner::class)
#SpringBootTest
#EmbeddedKafka // used on some kafka tests
class BasicTests {
and method:
#Test
fun `test method count`() {
// here I have a kafka producer sending a message to a topic that ends up
// calling myService.getSomeString via #KafkaListener from other services
verify(someObjectRelatedToMyService, atLeast(1)).getSome()
}
In the place of someObjectRelatedToMyService I tried to use
#Autowired
lateinit var myService: MyService
But then I got Argument passed to verify() is of type MyService and is not a mock!
But when I use
#Mock
lateinit var myMock: MyService
I get Actually, there were zero interactions with this mock.
And actually, to me it makes sense, since my mock wasn't called, but my real service at the application was.
Is it possible to count method calls from my real object?
You can spy on the real object to count method calls on it like this:
#Test
fun `test method count`() {
Mockito.spy(someObjectRelatedToMyService)
verify(someObjectRelatedToMyService, atLeast(1)).getSome()
}
As you can see, the only thing you have to do is to call the spy method which enables tracking interactions with the target object.
When adding this call before the verify method, you should not get the error anymore that the object is not a mock.
[Posting here since no rep to comment] Have you tried using a #Spy? Then you could specify which methods to mock and which methods to call. I supposed you can also apply Mockito.verify on spies...

How to create a TestContainers base test class in Kotlin with JUnit 5

I am trying to use Neo4j TestContainers with Kotlin, Spring Data Neo4j, Spring Boot and JUnit 5. I have a lot of tests that require to use the test container. Ideally, I would like to avoid copying the container definition and configuration in each test class.
Currently I have something like:
#Testcontainers
#DataNeo4jTest
#Import(Neo4jConfiguration::class, Neo4jTestConfiguration::class)
class ContainerTest(#Autowired private val repository: XYZRepository) {
companion object {
const val IMAGE_NAME = "neo4j"
const val TAG_NAME = "3.5.5"
#Container
#JvmStatic
val databaseServer: KtNeo4jContainer = KtNeo4jContainer("$IMAGE_NAME:$TAG_NAME")
.withoutAuthentication()
}
#TestConfiguration
internal class Config {
#Bean
fun configuration(): Configuration = Configuration.Builder()
.uri(databaseServer.getBoltUrl())
.build()
}
#Test
#DisplayName("Create xyz")
fun testCreateXYZ() {
// ...
}
}
class KtNeo4jContainer(val imageName: String) : Neo4jContainer<KtNeo4jContainer>(imageName)
How can I extract the databaseServer definition and the #TestConfiguration? I tried different ways of creating a base class and having the ContainerTest extend it, but it is not working. From what I understand, static attriubutes are not inherited in Kotlin.
Below my solution for sharing same container between tests.
#Testcontainers
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
abstract class IntegrationTest {
companion object {
#JvmStatic
private val mongoDBContainer = MongoDBContainer(DockerImageName.parse("mongo:4.0.10"))
.waitingFor(HostPortWaitStrategy())
#BeforeAll
#JvmStatic
fun beforeAll() {
mongoDBContainer.start()
}
#JvmStatic
#DynamicPropertySource
fun registerDynamicProperties(registry: DynamicPropertyRegistry) {
registry.add("spring.data.mongodb.host", mongoDBContainer::getHost)
registry.add("spring.data.mongodb.port", mongoDBContainer::getFirstMappedPort)
}
}
}
The key here is to not use #Container annotation as it will close just created container after your first test subclass executes all tests.
Method start() in beforeAll() initialize container only once (upon first subclass test execution), then does nothing while container is running.
By theory we shouldn't have to do this hack, based on:
https://www.testcontainers.org/test_framework_integration/junit_5/
...container that is static should not be closed until all of tests of all subclasses are finished, but it's not working that way and I don't know why. Would be nice to have some answer on that :).
I've had the same issue (making Spring Boot + Kotlin + Testcontainers work together) and after searching the web for (quite) a while I found this nice solution: https://github.com/larmic/testcontainers-junit5. You'll just have to adopt it to your database.
I faced very similar issue in Kotlin and spring boot 2.4.0.
The way you can reuse one testcontainer configuration can be achieved through initializers, e.g.:
https://dev.to/silaev/the-testcontainers-mongodb-module-and-spring-data-mongodb-in-action-53ng or https://nirajsonawane.github.io/2019/12/25/Testcontainers-With-Spring-Boot-For-Integration-Testing/ (java versions)
I wanted to use also new approach of having dynamicProperties and it worked out of a boxed in java. In Kotlin I made sth like this (I wasn't able to make #Testcontainer annotations working for some reason). It's not very elegant but pretty simple solution that worked for me:
MongoContainerConfig class:
import org.testcontainers.containers.MongoDBContainer
class MongoContainerConfig {
companion object {
#JvmStatic
val mongoDBContainer = MongoDBContainer("mongo:4.4.2")
}
init {
mongoDBContainer.start()
}
}
Test class:
#SpringBootTest(
classes = [MongoContainerConfig::class]
)
internal class SomeTest {
companion object {
#JvmStatic
#DynamicPropertySource
fun setProperties(registry: DynamicPropertyRegistry) {
registry.add("mongodb.uri") {
MongoContainerConfig.mongoDBContainer.replicaSetUrl
}
}
}
Disadvantage is this block with properties in every test class what suggests that maybe approach with initializers is desired here.