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

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
}

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>>)

Mocking Gradle javaexec calls with mockK

Currently a beginner with mockK as it relates to developing Gradle plugin code in Kotlin. Suppose I have this class:
abstract class MyDomainObjectClass #Inject constructor(private val execOps: ExecOperations) {
abstract val mainClass: Property<String>
fun run() {
execOps.javaexec {
// ...
}
}
}
What I want to do is to construct a MyDomainObjectClass (normally constructed using something like ObjectFactory.newInstance()) in such a way that I can pass in a mocked ExecOperations, so that I can verify that the javaexec call is called exactly once (with the verification possibly involving mainClass, if I can find a way to involve it).
Is there a way I can satisfy all these requirements, or am I better off with a constructed mock of MyDomainObjectClass (stubbing in mainClass in the process)?

Is it possible to disable inlining of value classes in Kotlin?

Goal
I would like to globally disable inlining of #JvmInline value class classes via a compiler flag or something similar. I would want to do this when running unit tests but not in production.
Motivation
I would like to use mockk with value classes.
I want to write a unit test that looks like this:
#JvmInline
value class Example(private val inner: Int)
class ExampleProvider {
fun getExample(): Example = TODO()
}
#Test
fun testMethod() {
val mockExample = mockk<Example>()
val mockProvider = mockk<ExampleProvider> {
every { getExample() } returns mockExample
}
Assert.assertEquals(mockExample, mockProvider.getExample())
}
This code fails with the following exception:
no answer found for: Example(#4).unbox-impl()
I think that if I were able to disable class inlining that this would no longer be an issue.

Gradle lazy Exec-Task configuration

I'm running into a problem when configuring an Exec-Task using an Extension-Property.
Problem
The configuration of my Exec-Task relies on a String-Property that is defined in an extension. Unfortunately, the property is not set yet, when configuring the Exec-Task. This leads to an TaskCreationException:
Could not create task ':myTask'.
org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':myTask'.
...
Caused by: org.gradle.api.internal.provider.MissingValueException: Cannot query the value of extension 'myConfig' property 'command' because it has no value available.
at org.gradle.api.internal.provider.AbstractMinimalProvider.get(AbstractMinimalProvider.java:86)
Example
abstract class ConfigExtension() {
abstract val command: Property<String>
}
class MyGradlePlugin : Plugin<Project> {
override fun apply(project: Project) {
val myConfig = project.extensions.create(
"myConfig",
ConfigExtension::class.java
)
val myTask = project.tasks.register(
"myTask",
Exec::class.java
) {
it.commandLine(myConfig.command.get())
}
}
}
The problem seems to be the myConfig.command.get() which circumvents the lazy evaluation.
Test
#Test fun `plugin registers task`() {
// Create a test project and apply the plugin
val project = ProjectBuilder.builder().build()
project.plugins.apply("com.example.plugin")
// Verify the result
assertNotNull(project.tasks.findByName("myTask"))
}
Question
Is there a way to configure the commandLine-Value in a lazy manner like gradle tasks should be configured? [1] [2]

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.