Skip to main content

Testing API (GPAL / Java)

Integration testing​

info

The older test-support classes (AbstractGenesisTestSupport, GenesisTestSupport, AbstractDatabaseTest and related classes) are deprecated in GSF 10.0, and GenesisJunit, described on this page, replaces them. Existing tests that use them still compile and run, with deprecation warnings. Write new tests with GenesisJunit. To move an existing test across, see the mapping to GenesisJunit on the legacy testing page.

Genesis provides a JUnit extension that helps developers write integration tests. From GSF 10.0, it runs on JUnit 6 (JUnit Jupiter 6.1); JUnit 4 is no longer supported. The extension will create a Genesis microservice for the duration of each test case. The GenesisJunit functionality is made available via the genesis-testsupport package. This page describes the GenesisJunit extension in general.

tip

Prefer using @GenesisTest or @GenesisDatabaseTest instead of @ExtendWith(GenesisJunit...). These annotations implicitly register the JUnit extension and are more concise.

Testing specific services​

In addition to general test support, GenesisJunit also provides support for specific services. For more information, have a look at the links below.

A simple example​

Let's have a look at a simple test. We have a TradeProcessor class that takes a trade Id, processes the trade and updates the status. We want to make sure our trade is marked as processed, once complete.

Here is the class. It has a constructor annotated with @Inject, which receives the database.

package com.example.trades

import global.genesis.db.rx.entity.multi.SyncEntityDb
import jakarta.inject.Inject

class TradeProcessor @Inject constructor(private val db: SyncEntityDb) {

fun processTrade(tradeId: String) {
// look up the trade, process it and set its status to TradeStatus.PROCESSED
}
}

And here is the test.

import com.example.trades.TradeProcessor
import com.example.trades.TradeStatus
import global.genesis.db.rx.entity.multi.SyncEntityDb
import global.genesis.gen.dao.Trade
import global.genesis.testsupport.jupiter.CsvData
import global.genesis.testsupport.jupiter.GenesisTest
import jakarta.inject.Inject
import org.junit.jupiter.api.Test

@GenesisTest // 1
@CsvData("my-trades.csv") // 2
class TradeProcessorTest {

@Inject
lateinit var db: SyncEntityDb // 3

@Inject
lateinit var tradeProcessor: TradeProcessor // 4

@Test
fun myTest() {
tradeProcessor.processTrade("TRADE_1") // 5

val dbTrade = db.get(Trade.byId("TRADE_1")) // 6

assert(dbTrade.status == TradeStatus.PROCESSED) // 7
}
}

Let's break down what happens here.

  1. @GenesisTest - using this annotation will enable the Genesis JUnit extension. It will manage the Genesis resources during the test.
  2. @CsvData("my-trades.csv") - our test relies on trade data existing in the database. Here we specify that data. @CsvData resolves file names as classpath resources, so my-trades.csv must live under src/test/resources in your test module (following the standard Gradle/JUnit convention), for example at src/test/resources/my-trades.csv.
  3. @Inject and SyncEntityDb - all classes available for injection during runtime are available in our test. Here we're getting a reference to the database.
  4. @Inject and TradeProcessor - we can also inject our own classes. TradeProcessor has a constructor annotated with @Inject, so the dependency injection mechanism knows how to instantiate it.
  5. By the time the test starts, our injected instances are available and we can start testing.
  6. We can access the database as we would normally to get the updated state of the trade.
  7. We verify that the trade status has been updated as expected.

GenesisJunit​

GenesisJunit will take care of the Genesis side of the test. There are two modes for running GenesisJunit:

  1. Full microservice
  2. Database only

The main benefit of using @GenesisTest is full microservice support. We can use the message client, package scan and process lifecycle. The main benefit of using @GenesisDatabaseTest is that tests run a lot faster.

It will do the following for each test:

FunctionDatabase onlyFull Micro service
Annotation to Use@GenesisDatabaseTest@GenesisTest
Instantiate the database✔️✔️
Load csv data✔️✔️
Package scan❌️✔️
Start a Genesis microservice❌️✔️
Inject properties into the test class✔️✔️
Run the test✔️✔️
Clean up resources✔️✔️

The @GenesisDatabaseTest and @GenesisTest can be found in the global.genesis.testsupport.jupiter package.

System definitions in tests​

By default, a Genesis test context — whether started via @GenesisTest/@GenesisDatabaseTest or via @GenesisSpringTest — does not read your project's real system-definition files. It builds an isolated, in-memory system-definition service, populated only from @SysDefOverwrite and @ProvidedSysDef. Editing your real genesis-system-definition.kts has no effect on such a test; any key not supplied by one of those two annotations simply resolves to its default.

The enableAppConfigInTests system property controls this behaviour for every Genesis test context, Spring or classic GenesisJunit alike:

  • false (the default) — use the isolated, in-memory system-definition service described above.
  • true — build the system-definition service from the real system-definition files found on the test classpath instead.

Enable it by passing -DenableAppConfigInTests=true to the test JVM.

Scenario Testing​

You can define and share scenarios for testing. You can do this by creating a class with genesis test annotations only. You can then import those scenarios by adding multiple @TestScenario(MyClass::class) or @TestScenario(MyClass.class) to your tests. Finally, you will need to annotate your test functions with @GenesisTemplateTest. Your test will now be run against those multiple scenarios. In the example below, the code is tested with both Flag set to true and false using system definition overrides. However, the use is not limited to @SysDefOverwrite, you will be able to use any configuration that drives the configuration of the service and or database.

@SysDefOverwrite("Flag", "true")
class ScenarioA

@SysDefOverwrite("Flag", "false")
class ScenarioB

@GenesisDatabaseTest
@TestScenario(ScenarioA::class)
@TestScenario(ScenarioB::class)
class ScenarioExample {

@GenesisTemplateTest
fun name() {
// test here...
}
}

Re-using resources between tests​

Often, most test time is spent provisioning and tearing down the microservice or database. However, this is not always strictly necessary. For instance, if you are testing how your trade microservice handles different trades, those tests can likely run without restarting the service in between. Please see the equivalent annotations for microservice and database-only tests below:

Test TypeContext per testShared Context
Microservice@GenesisTest@GenesisSharedContextTest
Database only@GenesisDatabaseTest@GenesisDatabaseTest(reuseDatabase = true)

These tests will behave slightly differently.

Microservice shared context​

When using @GenesisSharedContextTest, function-level annotations are not supported, except @CsvData and @ResetTableAfterTest. Your test will fail if any other GenesisJunit annotation is found on a test function. Data loaded by a function-level @CsvData is reverted after that test. Additionally, after each test, if the service is no longer healthy or if exit was called, any subsequent test will fail.

Database only shared context​

Database tests behave slightly differently. Function level annotations are supported. GenesisJunit will attempt to reuse the database on a best-effort basis. Tests are run in sequence; this sequence is determined by JUnit. Between tests, GenesisJunit will check whether the database configuration is compatible between test functions. If compatible, the database will be reused; otherwise, it will be disregarded and a new database will be initialised.

Annotations​

GenesisJunit supports a range of annotations.

important

You must add @GenesisDatabaseTest or @GenesisTest to your class or function. This is essential.

@GenesisDatabaseTest, @GenesisTest and the annotations below can be applied to the targets listed in the table. Not all annotations are supported when using @GenesisDatabaseTest.

AnnotationTargetRepeatableWorks with @GenesisDatabaseTest
GenesisTestClass/ Method❌❌
GenesisDatabaseTestClass/ Method❌✔️
CoroutinesDumpOnFailureClass/ Method❌✔️
CsvDataClass/ Method✔️✔️
EnableDataDumpClass/ Method❌❌
EnableInMemoryTestAuthCacheClass/ Method❌❌
EnableLegacyXmlDictionaryClass/ Method❌✔️
EnableQuietModeClass/ Method❌✔️
EnableTestClassLoaderClass/ Method❌️❌️
ExpectedExitCodeClass/ Method❌️❌️
ExpectedProcessStatusMethod❌️❌
FullDumpOnFailureClass/ Method❌✔️
GenesisHomeClass/ Method❌✔️
GenesisSharedContextTestClass❌❌
GenesisTemplateTestMethod❌✔️
NetworkConfigClass/ Method❌❌
PackageNameScanClass/ Method✔️❌
PackageScanClass/ Method✔️❌
ProcessArgClass/ Method❌❌
ProvidedDictionaryField/ Method❌✔️
ProvidedInstanceField/ Method❌✔️
ProvidedSysDefField/ Method❌✔️
ProvidedTypeField/ Method❌✔️
ResetTableAfterTestClass/ Method❌❌
RootLogLevelClass/ Method❌❌
SysDefOverwriteClass/ Method✔️✔️
TestInjectMethod parameter❌✔️
TestConfigFileClass/ Method❌❌
TestScenarioClass/ Method✔️✔️
TestScriptFileClass/ Method✔️❌
ThreadDumpOnFailureClass/ Method❌✔️
UserRightClass/ Method✔️❌
WithLogLevelClass/ Method✔️✔️

Some annotations are repeatable, which means you can provide multiple values at the class or method level.

  • If you provide these Repeatable annotations on both the class and method level, both are applied.
  • If you provide non-Repeatable annotations on both the class and method level, the method-level annotation takes precedence.
  • The enable annotations (EnableDataDump and EnableInMemoryTestAuthCache) do not support disabling at the method level once they have been enabled on the class level.

All annotations can be found in the global.genesis.testsupport.jupiter package, except @WithLogLevel, which is in global.genesis.test.log4j.

CsvData​

This annotation is used to load CSV data as part of a test and is also repeatable. Both individual file paths and folder paths are accepted. In terms of individual files, the DumpIt CSV format is supported in both .csv and .csv.gz extensions.

Alternatively, multi-table DumpIt format is supported in the following format:

#TABLE_NAME
COLUMN_NAME1, COLUMN_NAME2, COLUMN_NAME3
COLUMN_VALUE1, COLUMN_VALUE2, COLUMN_VALUE3
COLUMN_VALUE2, COLUMN_VALUE3, COLUMN_VALUE4

So, assuming two tables named FIRST_TABLE and SECOND_TABLE, both with String columns ID and TEXT, both containing 2 records each, a sample file would look like this:

#FIRST_TABLE
ID,TEXT
id1,text1
id2,text2
#SECOND_TABLE
ID,TEXT
id1,text1
id2,text2
@GenesisTest
@CsvData("my-data.csv")
internal class CsvDataExamples {

@Test
fun loadCsvData() {
// just uses "my-data.csv"
}

@Test
@CsvData("other-data.csv.gz")
fun loadCsvDataFromOtherDataFile() {
// uses "my-data.csv" and "other-data.csv.gz"
}

@Test
@CsvData("other-data.csv.gz")
@CsvData("data-folder")
fun loadCsvDataFromMultipleFiles() {
// uses "my-data.csv", "other-data.csv.gz" and the "data-folder" folder
}
}

EnableDataDump​

This annotation will enable the DATADUMP log level in the microservice. This will output any messages sent and received to the logger. You can apply this annotation on both classes and methods. However, once enabled on the class level, there is no way to disable on the method level.

@GenesisTest
@EnableDataDump
class DataDumpTest {

@Test
@EnableDataDump
fun myTest() {
// ...
}
}

EnableInMemoryTestAuthCache​

This annotation enables the in-memory auth cache. To set or remove entity authorisation, you will need to inject an InMemoryTestAuthCache into your class. You can apply this annotation on both classes and methods. However, once enabled on the class level, there is no way to disable on the method level.

import global.genesis.testsupport.jupiter.EnableInMemoryTestAuthCache
import global.genesis.testsupport.jupiter.GenesisTest
import global.genesis.testsupport.mock.InMemoryTestAuthCache

@GenesisTest
@EnableInMemoryTestAuthCache
internal class EnableInMemoryTestAuthCacheExamples {

/**
* inject [InMemoryTestAuthCache] to programmatically change authorisations
*/
@Inject
lateinit var authCache: InMemoryTestAuthCache

@BeforeEach
fun setUp() {
// Clear the entire auth map before each test
authCache.clear("TRADE_VISIBILITY")
}

@Test
fun testAuthoriseAndRevokeAuthCache() {
// to authorise:
authCache.authorise(
authMap = "TRADE_VISIBILITY",
entityCode = "00000000001TRSP0",
userName = "JohnDoe"
)

// and then revoke authorisation:
authCache.revoke(
authMap = "TRADE_VISIBILITY",
entityCode = "00000000001TRSP0",
userName = "JohnDoe"
)
}
}

EnableLegacyXmlDictionary​

This annotation enables the legacy XML dictionary from the provided Genesis home folder for the test. This is only necessary when testing against test-specific dictionaries. By default, an application's dictionary is loaded, ensuring consistency between production and test dictionaries without needing to duplicate the dictionary files. To define a test dictionary inline in Kotlin instead, use @ProvidedDictionary.

import global.genesis.testsupport.jupiter.EnableLegacyXmlDictionary
import global.genesis.testsupport.jupiter.GenesisTest
import org.junit.jupiter.api.Test

@GenesisTest
@EnableLegacyXmlDictionary
class LegacyXmlDictionaryTest {
@Test
fun myTest() {
// legacy XML dictionary is enabled
}
}

EnableQuietMode​

This annotation disables the update queue during the test. It applies to @GenesisDatabaseTest tests only; a @GenesisTest ignores it. This annotation can be applied to classes or methods and is not Repeatable.

@GenesisDatabaseTest
@EnableQuietMode
class QuietModeTest {
@Test
fun myTest() {
// test runs in quiet mode
}
}

EnableTestClassLoader​

This annotation enables the test class loader for the test. This is only needed in edge cases where a class may dynamically load classes. This annotation can be applied to classes or methods.

@GenesisTest
@EnableTestClassLoader
class TestClassLoaderTest {
@Test
fun myTest() {
// test class loader is enabled
}
}

ExpectedExitCode​

The ExpectedExitCode annotation provides a way to assert the expected exit code of a process after a test. This is useful when testing failure scenarios. By default, a test will fail if a process tries to exit.

@Test
@ExpectedExitCode(1)
fun `test expected exit code`() {
// test code that should exit with code 1
}

ExpectedProcessStatus​

The ExpectedProcessStatus annotations provide a way to assert the end state of a process after a test. By default, GenesisJunit will assert that the process is healthy (ProcessState.UP).

@Test
@ExpectedProcessStatus(ProcessState.DOWN)
fun `test status DOWN`() {
ProcessStateChangeHandler("test").setProcessDown()
}

GenesisDatabaseTest​

Annotation used to enable a database-only context for faster tests. Provides DI and CSV loading but does not start a microservice. Non-repeatable.

@GenesisDatabaseTest
class MyDbOnlyTest {
@Inject
lateinit var db: SyncEntityDb

@Test
fun myTest() { /* ... */ }
}

GenesisHome​

Annotation used to specify the Genesis home directory path. It can be applied to classes or functions/methods. If the annotation is not provided, genesis home will default to /genesisHome. Providing this annotation at the method level will take precedence over the class level annotation.

@GenesisTest
@GenesisHome("/genesisHomeA")
class GenesisHomeTest {

@Test
fun myTest() {
// this test uses genesisHomeA
}

@Test
@GenesisHome("/genesisHomeB")
fun myOtherTest() {
// this test uses genesisHomeB
}
}

GenesisSharedContextTest​

Annotation used to enable the full microservice context that is shared between tests within a class. Provides DI, package scanning, message client, and lifecycle management. Non-repeatable. In the example, the microservice is started only once, and used by both myTest and myOtherTest.

import global.genesis.testsupport.jupiter.GenesisSharedContextTest
import org.junit.jupiter.api.Test

@GenesisSharedContextTest
class MyGenesisTest {
@Test
fun myTest() { /* ... */ }
@Test
fun myOtherTest() { /* ... */ }
}

GenesisTemplateTest​

Used with scenario testing to execute the same test method across one or more scenarios, and is used in combination with @TestScenario. For more information see Scenario Testing Apply at method level only.

@GenesisDatabaseTest
@TestScenario(ScenarioA::class)
@TestScenario(ScenarioB::class)
class MyTemplateTests {
@GenesisTemplateTest
fun runAcrossScenarios() { /* ... */ }
}

GenesisTest​

Annotation used to enable the full microservice context for a test. Provides DI, package scanning, message client, and lifecycle management. Non-repeatable.

@GenesisTest
class MyGenesisTest {
@Test
fun myTest() { /* ... */ }
}

PackageNameScan​

Annotation used to specify package names for scanning. Unlike @PackageScan, this annotation accepts String rather than Class. This annotation should be used to mark classes or functions that require package scanning by name. This annotation is Repeatable.

@GenesisTest
@PackageNameScan("com.example.package")
internal class PackageNameScanTest {
@Test
fun myTest() {
// scans the package "com.example.package"
}
}

ProvidedSysDef​

Annotation used to mark properties or methods as provided system definitions. The annotation takes the system definition key, and the value of the marked property, or the return value of the marked no-argument method, becomes that key's value during test runtime.

@GenesisTest
internal class ProvidedSysDefTest {

@ProvidedSysDef("MY_SYS_DEF")
private val mySysDef: String = "test-value"

@Test
fun myTest() {
// the MY_SYS_DEF system definition is set to "test-value"
}
}

PackageScan​

Annotation used to mark classes or functions for package scanning. This annotation should be used to mark classes or functions that require package scanning. It is used to specify the marker interface or class to be used for scanning packages. This annotation is Repeatable.

@GenesisTest
@PackageScan(MyClass::class)
internal class PackageScanTest {
@Test
fun myTest() {
// scans the package of MyClass
}

@Test
@PackageScan(MyOtherClass::class)
fun myOtherTest() {
// scans the package of MyClass and MyOtherClass
}

@Test
@PackageScan(MyOtherClass::class)
@PackageScan(MyThirdClass::class)
fun myThirdTest() {
// scans the package of MyClass, MyOtherClass and MyThirdClass
}
}

ProcessArg​

Annotation used to provide process arguments, as would be passed on the command line to a real Genesis process. The arguments are made available to the test process via ProcessArguments. This annotation can be applied to classes or functions and is not Repeatable. Providing this annotation at the method level will take precedence over the class level annotation - this is true even if the method level annotation provides no arguments, which clears any arguments provided at the class level for that test. This annotation is not supported when using @GenesisDatabaseTest, as no process is bootstrapped in that mode.

@GenesisTest
@ProcessArg("--coldStart")
internal class ProcessArgTest {

@Test
fun myTest() {
// the unit test service is started with process argument "--coldStart"
}

@Test
@ProcessArg("--coldStart", "TABLE_NAME")
fun myOtherTest() {
// the unit test service is started with process arguments "--coldStart" and "TABLE_NAME",
// replacing the class-level arguments for this test
}

@Test
@ProcessArg
fun myThirdTest() {
// the unit test service is started with no process arguments for this test
}
}

ProvidedDictionary​

Marks a property or a no-argument method that returns the GenesisDictionary for the test, in place of the application's production dictionary. Use it when a test needs tables of its own that the production dictionary doesn't define. The providedDictionary { } helper builds the dictionary from an inline table definition, in the same syntax as a tables { } block. A field declared without a type is a STRING. It is a Kotlin function, so write the provider member in Kotlin.

import global.genesis.db.DbRecord
import global.genesis.db.SyncDb
import global.genesis.dictionary.GenesisDictionary
import global.genesis.testsupport.jupiter.GenesisTest
import global.genesis.testsupport.jupiter.ProvidedDictionary
import global.genesis.testsupport.jupiter.providedDictionary
import jakarta.inject.Inject
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals

@GenesisTest
class ProvidedDictionaryTest {

@ProvidedDictionary
fun dictionary(): GenesisDictionary = providedDictionary {
table(name = "MY_TEST_TABLE", id = 1) {
field("ID").primaryKey()
field("AGE", INT)
}
}

@Inject
lateinit var db: SyncDb

@Test
fun myTest() {
// the dictionary holds MY_TEST_TABLE, PROCESS_STATIC_INFO and PROCESS_META_DATA
// MY_TEST_TABLE has no generated entity class, so use DbRecord to write and read a row
db.insert(DbRecord.dbRecord("MY_TEST_TABLE") { setString("ID", "A") })
val row = db.get(DbRecord.dbRecord("MY_TEST_TABLE") { setString("ID", "A") })
assertEquals("A", row?.getString("ID"))
}
}
  • providedDictionary { } adds the PROCESS_STATIC_INFO and PROCESS_META_DATA tables for you. Ids 10001 and 10002 are reserved for these tables, so do not use them for your own tables.
  • A test class, including its superclasses, can have only one @ProvidedDictionary member. A second one fails the test with Only one @ProvidedDictionary member is supported, found: …, followed by the names of the members it found.
  • You can't combine it with @EnableLegacyXmlDictionary. The test fails with @ProvidedDictionary cannot be combined with @EnableLegacyXmlDictionary.
  • A method must take no parameters and must not be a @Test method itself.
  • If the member returns null or something other than a GenesisDictionary, the test fails with <class>.<member> is annotated @ProvidedDictionary but does not provide a GenesisDictionary, where <class>.<member> is the fully qualified class name and the member name. It never falls back to the production dictionary.
  • @GenesisSharedContextTest builds its context from the class, before any test instance exists. There, put the member in a companion object: either a property, or a function annotated @JvmStatic. An instance member fails with a message telling you to use a static member.
  • If the table definition doesn't build, the test fails with Error while reading provided dictionary: followed by the problems found.

To inspect the active dictionary, inject GenesisDictionary into the test. For example, to check that the added tables are present:

import kotlin.test.assertTrue

@Inject
lateinit var dict: GenesisDictionary

@Test
fun dictionaryHasProvidedTables() {
assertTrue(dict.containsTable("MY_TEST_TABLE"))
assertTrue(dict.containsTable("PROCESS_STATIC_INFO"))
assertTrue(dict.containsTable("PROCESS_META_DATA"))
}

In Java, declare the field as @Inject GenesisDictionary dict; and call the same containsTable method.

@GenesisSharedContextTest
class SharedProvidedDictionaryTest {

companion object {
@JvmStatic
@ProvidedDictionary
fun dictionary(): GenesisDictionary = providedDictionary {
table(name = "MY_TEST_TABLE", id = 1) {
field("ID").primaryKey()
}
}
}
}

ProvidedInstance​

Annotation used to mark properties or methods as provided instances. Marked properties or methods can be used to override predefined instances during test runtime.

For example, one could define an interface in production code called MyInterface with a default implementation MyInterfaceImpl.


interface MyInterface

@Module
@ConditionalOnMissingClass(MyInterface::class)
class MyInterfaceImpl: MyInterface

Then we can override the implementation at runtime using a fake/mock implementation:

@GenesisTest
internal class ProvidedInstanceTest {

/**
* Provides a [MyInterface] instance during the dependency injection phase.
*/
@ProvidedInstance
private val myInstance: MyInterface = FakeImpl()

@Test
fun myTest() {
//
}
}
note

@ProvidedInstance is for instances you have already built. Providing a class here instead (for example MyClass::class) is deprecated: it still works, but each such member logs a warning that it will be rejected in a future release. Use @ProvidedType for a class you want Guice to build.

ProvidedType​

Marks a property or a no-argument method that returns a class (a KClass in Kotlin, a Class in Java). Guice builds and binds that class for the test, as it would if @PackageScan had found it, but without scanning a package. Use @ProvidedInstance when you already have the instance. If the value isn't a class, the test fails with <member> is annotated @ProvidedType but provides <type>; it must provide a KClass (where <type> is null for a null value).

@GenesisTest
internal class ProvidedTypeTest {

@ProvidedType
private val myType = MyClass::class

@Inject
lateinit var myClass: MyClass

@Test
fun myTest() {
// MyClass is built and bound by Guice, so it can be injected and used
myClass.doSomething()
}
}

In a @GenesisSharedContextTest, no test instance exists when these members are read, so put the member in a companion object in Kotlin: either a property, or a function annotated @JvmStatic. In Java, declare the field or method static. An instance member fails the test with a message telling you to use a static member. A member that returns null, or a method that takes parameters, also fails the test. @ProvidedInstance is less strict: it skips such a member without a message.

@GenesisSharedContextTest
class SharedProvidedTypeTest {

companion object {
@ProvidedType
val myType = MyClass::class
}
}

ResetTableAfterTest​

Annotation used to reset specific database tables after each test when using a @GenesisSharedContextTest. GenesisJunit will take a snapshot of the table before each test, and then revert it to its previous state. Please note that there is a limit of 1,000 rows; the test will fail if a table has more rows than this. The snapshot will be taken after any @CsvData is loaded, but before the test is run. This annotation can be applied to classes or methods. It is not Repeatable; to reset several tables, list them in one annotation, for example @ResetTableAfterTest("TRADE", "POSITION").

@GenesisSharedContextTest
@ResetTableAfterTest("TRADE")
@CsvData("trade.csv")
internal class ResetTableAfterTestExample {
@Test
fun myTest() {
// TRADE table will be reset after this test
}
@Test
fun myTest2() {
// TRADE table will be reset after this test
}
}

RootLogLevel​

This annotation will adjust the log level for the life of the test. You can apply this annotation on both classes and methods. Providing this annotation at the method level will take precedence over the class level annotation.

import global.genesis.testsupport.jupiter.GenesisTest
import global.genesis.testsupport.jupiter.RootLogLevel
import org.junit.jupiter.api.Test
import org.slf4j.event.Level

@GenesisTest
@RootLogLevel(Level.INFO)
class LogLevelTest {

@Test
fun myTest() {
// root log level set to INFO
}

@Test
@RootLogLevel(Level.TRACE)
fun myOtherTest() {
// root log level set to TRACE
}
}

WithLogLevel​

Sets the level of a named logger for the duration of a test class or method, and puts the previous level back afterwards. Unlike @RootLogLevel, which sets the root level of a GenesisJunit process, @WithLogLevel targets one logger, and it is a plain JUnit extension: it works with or without the Genesis test annotations. The annotation registers its own JUnit extension.

  • It is in the global.genesis.test.log4j package, not global.genesis.testsupport.jupiter. It comes with genesis-testsupport, so you don't need another dependency.
  • logger is a logger name: a package or a class. WithLogLevel.PACKAGE (an empty string) means the test class's package.
  • level takes a LogLevel: TRACE, DEBUG, INFO, WARN, ERROR or FATAL. SLF4J has no FATAL level, so to check FATAL read the logger through log4j: org.apache.logging.log4j.LogManager.getLogger("com.example.trades").isFatalEnabled.
  • The annotation is repeatable, so you can set several loggers at once.
  • A class-level annotation applies before the class's tests start, so it also covers Genesis start-up, which happens before each test. Another extension's class-level set-up is covered only if @WithLogLevel is declared above it. A method-level annotation overrides it for that test.
  • It works with log4j, and with logback when log4j isn't the active logging backend (see Step 3: Switch logging to Logback). On logback, FATAL is applied as ERROR.
package com.example.tests

import global.genesis.test.log4j.LogLevel
import global.genesis.test.log4j.WithLogLevel
import global.genesis.testsupport.jupiter.GenesisTest
import org.junit.jupiter.api.Test
import org.slf4j.LoggerFactory
import kotlin.test.assertTrue

@GenesisTest
@WithLogLevel(logger = "com.example.trades", level = LogLevel.DEBUG)
class WithLogLevelTest {

@Test
fun myTest() {
// com.example.trades logs at DEBUG
assertTrue(LoggerFactory.getLogger("com.example.trades").isDebugEnabled)
}

@Test
@WithLogLevel(logger = "com.example.trades", level = LogLevel.TRACE)
@WithLogLevel(logger = WithLogLevel.PACKAGE, level = LogLevel.DEBUG)
fun myOtherTest() {
// com.example.trades logs at TRACE, and the test class's package at DEBUG
assertTrue(LoggerFactory.getLogger("com.example.trades").isTraceEnabled)
assertTrue(LoggerFactory.getLogger(WithLogLevelTest::class.java.packageName).isDebugEnabled)
}
}

NetworkConfig​

Without this annotation, a test process reads a network-config.yaml or network-config-PROCESS_NAME.yaml from its GENESIS_HOME, as a deployed process does (see Service encryption). The file replaces the ChannelType and MessageSerialization system definitions, and a tls mode of TLS or MUTUAL_TLS starts the test process with TLS. Relative TLS paths in the file resolve against the test GENESIS_HOME. With no file, the system definitions apply, defaulting to WebSocket and JSON.

@NetworkConfig points the test process at a network config file of your choice instead. The path is a classpath resource; if no resource matches, it is read as a filesystem path. The file is read exactly as a network-config.yaml under GENESIS_HOME is. The annotated file wins outright: a file under the test GENESIS_HOME and the ChannelType and MessageSerialization system definitions are both ignored. You can apply this annotation on both classes and methods.

@GenesisTest
@GenesisHome("/GenesisHome")
@NetworkConfig("/network-configs/websocket.yaml")
class NetworkConfigTradeAppTest {

@Inject
private lateinit var networkConfig: NetworkConfigContainer

@Test
fun `the annotated file supplies the network config`() {
assert(networkConfig.messaging.channel == ChannelType.WEBSOCKET)
}
}

SysDefOverwrite​

Annotation used to indicate that a specific system definition property should be overwritten. This annotation can be applied to classes or functions. When specifying this annotation on both the class and the function level, both will be taken into account, unless the same property is overwritten, in which case the method-level annotation will take precedence.

@GenesisTest
@SysDefOverwrite("MY_VALUE", "ABC")
internal class OverwriteSysDefTest {

@Test
fun simpleExample() {
// MY_VALUE is set to ABC
}

@Test
@SysDefOverwrite("OTHER_VALUE", "DEF")
fun multipleLevels() {
// MY_VALUE is set to ABC, OTHER_VALUE is set to DEF
}

@Test
@SysDefOverwrite("OTHER_VALUE", "DEF")
@SysDefOverwrite("MY_VALUE", "GHI")
fun overwritingClassLevelSysDef() {
// MY_VALUE is set to GHI, OTHER_VALUE is set to DEF
}
}
tip

When running genesis integration tests, by default, all injecting modules will run on a process named UNIT_TEST_PROCESS. However, in some cases, you may want to override this default process name to use a different one. You can do this by simply overriding the PROCESS_NAME system definition property. The property will be picked up regardless of how you choose to set up your system definitions.

@GenesisTest
class MyTest {
@Test
@SysDefOverwrite("PROCESS_NAME", "SOME_CUSTOM_PROCESS_NAME")
fun `test`() {
// Your test code here
}
}

TestConfigFile​

Use this annotation to load a process config file as part of a test. This annotation is not Repeatable.

@GenesisTest
@TestConfigFile("my-process-config.kts")
internal class ConfigFileExamples {

@Test
fun myProcessConfig() {
// just uses "my-process-config.kts"
}

@Test
@TestConfigFile("other-process-config.kts")
fun otherProcessConfig() {
// uses "other-process-config.kts"
}
}

TestScenario​

Annotation used to define and share test scenarios, and is used in combination with @GenesisTemplateTest. This annotation can be applied to classes or methods and is Repeatable. For more information see Scenario Testing

@GenesisTest
@TestScenario(MyScenarioA::class)
@TestScenario(MyScenarioB::class)
class TestScenarioExample {
@GenesisTemplateTest
fun myTest() {
// test runs twice, once with MyScenarioA and once with MyScenarioB
}
}

TestScriptFile​

Use this annotation to load a script file as part of the test. This annotation is Repeatable.

A bare file name, such as my-eventhandler.kts, is looked up at scripts/<name> or at the root of the test resources (src/test/resources/). A script anywhere else needs its path relative to the test resources root, for example @TestScriptFile("genesis/scripts/my-eventhandler.kts").

Alternatively, you can test using compiled GPAL definitions (classes extending GPalDataserver, GPalEventHandler, and so on). Ensure the definition's package is in the scan list (e.g. by providing an instance of the definition class). In that case no script file and no @TestScriptFile are required.

@GenesisTest
@TestScriptFile("my-eventhandler.kts")
internal class ScriptFileExamples {

@Test
fun testScriptFileExamples() {
// just uses "my-eventhandler.kts"
}

@Test
@TestScriptFile("other-eventhandler.kts")
fun testMoreScriptFiles() {
// uses "my-eventhandler.kts" and "other-eventhandler.kts"
}

@Test
@TestScriptFile("other-eventhandler.kts")
@TestScriptFile("more-eventhandler.kts")
fun testManyScriptFiles() {
// uses "my-eventhandler.kts", "other-eventhandler.kts" and "more-eventhandler.kts"
}
}

TestInject​

Annotation used to inject test dependencies into test functions as parameters. This is useful where you might want to use and or instantiate classes for some tests but not others.

@GenesisTest
class TestInjectExample {
@Test
fun myTest(@TestInject myTestDependency: MyTestDependency) {
// MyTestDependency is injected
}
}

UserRight​

The UserRight annotation provides users with specific rights during a test.

To use this annotation, annotate any method or class with @UserRight and provide the user and right codes:

@Test
@UserRight("John Doe", "LICENSE_TO_BILL")
fun `user has rights`() {
client.sendRequest(
workFlow = InstrumentDetailsFlow,
request = ByAlternateTypeAlternateCode("RIC", "AMBV4"),
username = "John Doe"
)
}

Troubleshoot threading and coroutine issues in tests​

To help troubleshoot threading and coroutine issues, GenesisJunit offers support for thread and coroutine dumps on test failure. To enable this, there are three annotations:

ThreadDumpOnFailure​

Dumps all JVM threads to the test logs on test failure. Useful to troubleshoot deadlocks and blocked tests. Non-repeatable.

@GenesisTest
class DumpOnFailureTest {
@Test
@ThreadDumpOnFailure
fun myTest() { /* ... */ }
}

CoroutinesDumpOnFailure​

Dumps Kotlin coroutines debug information to the test logs on failure. Useful for diagnosing coroutine leaks or stuck jobs. Non-repeatable.

@GenesisTest
class CoroutinesDumpTest {
@Test
@CoroutinesDumpOnFailure
fun myTest() { /* ... */ }
}

FullDumpOnFailure​

Combines thread and coroutine dumps on test failure. Non-repeatable.

@GenesisTest
class FullDumpTest {
@Test
@FullDumpOnFailure
fun myTest() { /* ... */ }
}

Component testing​

There are two easy ways of testing components in your application:

  • using an API client
  • using the curl tool from the command line

Before you start​

Before you start, make sure your server is running. Then run mon to check that your particular component’s process is running. For example, if you want to test one or more requestReply codeblocks (i.e. resources) in your Request Server, check that the application_REQUEST_SERVER process is running.

For any testing, you need to know:

  • the IP address or name of your server
  • the username and password that will enable you to log in and authenticate yourself

Using an API client​

This type of software offers an easy way of testing each of your resources.

Two clients that Genesis uses for component testing are:

Broadly speaking, Postman offers more features, but Insomnia is also good and is simpler to use.

Logging in​

Whichever client you are using, you need to log in before you can send test requests to the server. This involves two things:

  • providing a SOURCE_REF - this can be any string that identifies all your activity while you are logged in
  • retrieving a SESSION_AUTH_TOKEN, which you can copy and use to authorise all your test requests

For example, to log in using Insomnia:

  1. Create a new query in Insomnia.
  2. In front of the URL, set the call to POST.
  3. For the URL, you need to supply your server instance, then :9064 (to route to the application's router), and then event-login-auth. For example: https://test-mynewapp:9064/event-login-auth
  4. Set the body to JSON and paste the request below (substituting your correct username and password) in the main body.
{
"MESSAGE_TYPE": "TXN_LOGIN_AUTH",
"SERVICE_NAME": "AUTH_MANAGER",
"DETAILS": {
"USER_NAME": "DonJuan",
"PASSWORD": "Password123"
}
}
  1. Click to view the headers, then add SOURCE_REF. For this field, you can use any string that will identify you. In the example below, we set SOURCE_REF to BAUDOIN1.

  1. When you have done this, click on the Send button.

This returns a set of details in the right side of the Insomnia window, where you can copy the SESSION_AUTH_TOKEN, which you will need for your test requests.

Testing with curl​

You can use the curl tool to test a module from the command line.

The simple example below tests the resource event-account-validate-request. It sends a request to see if this resource in the Event Handler is able to validate an account.

curl --request POST 'localhost:9064/event-account-validate-request' \
--header 'SOURCE_REF: 1' \
--header "SESSION_AUTH_TOKEN: $1" \
--header 'Content-Type: application/json' \
-d '{"DETAILS": {"ACCOUNT_ID" : 9 }}'

Now let's look more closely at that.

  • At the beginning, we use the --request parameter, which specifies a custom request, followed by POST to indicate that we are posting data to the resource. The data itself comes later (in the -d parameter).

  • The resource that you are accessing must be part of the URL. In this case, the resource is event-account-validate-request. (Remember that the events you specify are transformed when you generate the objects. For example, EVENT_NAME becomes event-name.)

  • Three --header parameters have been specified:

    • The first header, SOURCE_REF, uniquely identifies your message. In our example, this is simply 1.

    • The SESSION_AUTH_TOKEN is required because, as is usually the case, the resource is non-public; you need to be logged in for access.

    • The Content-Type ... header indicates the media type of the content you are sending or requesting — for example, JSON or a PNG file. This tells the server how to handle your message. You can find more about content type.

  • The -d parameter specifies the input for the resource. The request body is always JSON and should always be contained in the DETAILS field. In this case, we are requesting to validate account ID 9.

Now here is a more complex example, which tests the ability to upsert to an eventHandler resource called event-upsert-inventory.

curl --request POST 'myserver-dev-fictional/ws/event-upsert-inventory' \
--header 'SOURCE_REF: 15' \
--header 'Content-Type: application/json' \
--header 'SESSION_AUTH_TOKEN: SnpTI4dvX9gcXDd4BQlOTkp4JSCrXR3t' \
--data-raw '{
"MESSAGE_TYPE": "EVENT_UPSERT_INVENTORY",
"SERVICE_NAME":"FOXTROT_EVENT_HANDLER",
"DETAILS":{
"INSTRUMENT_ID": "8200",
"INSTRUMENT_ID_TYPE": "FOXTROT_ID",
"UNIT_OFFER_PRICE":"102.55",
"UNIT_OFFER_SIZE": "1000000",
"UNIT_BID_PRICE":"100",
"UNIT_BID_SIZE": "2000000",
"PARTIAL_BID_ALLOWED": "TRUE",
"PARTIAL_OFFER_ALLOWED": "TRUE",
"IOI_ID" : "12345",
"TRADER_NAME" : "Ronald.Zappa@madeup.com"
}
}'

Note that the data to be upserted is specified using the --data-raw parameter. This is because the set of fields is reasonably complicated, and it includes an email address — you don't want that @ character to trigger any unwanted processing.

You can find more details about curl parameters online.

The Postman tool has a useful feature tucked away with the icons at the right of the screen. This enables you to automatically translate the query you have built into curl format (or many others).

In the area displayed, just select cURL as the code, and the code for your current query is displayed below for you to copy.