Skip to main content

Legacy Testing API

Deprecated in 10.0

The test-support classes on this page are still part of Genesis Server Framework (GSF) 10.0, but they are deprecated. Existing tests that use them still compile and run, with deprecation warnings when you build them.

The deprecated classes are AbstractGenesisTestSupport, GenesisTestSupport, GenesisClassGenerationTestSupport, GenesisTestConfig, DataServerTest, EventResponse, AbstractDatabaseTest and SimpleQueueAbstractDatabaseTest. The Java classes among them (GenesisTestSupport, GenesisClassGenerationTestSupport and AbstractDatabaseTest) are deprecated since 10.0.0 and marked for removal in a future release.

Write new tests with the annotation-based GenesisJunit API (@GenesisTest, @GenesisSharedContextTest and @GenesisDatabaseTest), and move existing tests to it when you can. See the Testing API page.

Mapping to GenesisJunit​

Most settings of the legacy test configuration have an equivalent in the annotation-based GenesisJunit API. Use this table to move a test across. The annotations are in the global.genesis.testsupport.jupiter package and are described on the Testing API page.

LegacyGenesisJunit
extends AbstractGenesisTestSupport / GenesisTestSupport@GenesisTest (a fresh process per test method) or @GenesisSharedContextTest (one process per class)
packageName / packageNames@PackageScan(SomeClass::class) or @PackageNameScan("...")
genesisHome@GenesisHome("...")
scriptFileName@TestScriptFile("...") (repeatable)
configFileName@TestConfigFile("...")
sendMessage / sendMessageAsyncInject a GenesisMessageClient (@Inject), which the test context provides to every @GenesisTest. This is the generic route: for a service with its own client (such as an event handler, with EventClientSync), prefer that client instead, as described in the parser row below. That client takes the event as a typed object; a test that keeps building GenesisSets stays on GenesisMessageClient. See sending messages in a GenesisJunit test
parser / EventResponseNot needed: inject the client for the service you are testing. Use EventClientSync (or EventClientAsync) for event handlers, RequestClientSync (or RequestClientAsync) for request servers, and DataServerSubscriptionClientAsync or DataServerQueryViewClient for data servers. See testing specific services
initialDataFile / initialDataFiles@CsvData("...") (repeatable)
authCacheOverride / authCacheOverrides@EnableInMemoryTestAuthCache, and inject InMemoryTestAuthCache. The auth map name is now passed per call with GenesisJunit, authCache.authorise(authMap = …, entityCode = …, userName = …), not set as configuration
useTempClassloader = true, or GenesisClassGenerationTestSupport@EnableTestClassLoader
dataDumpOn@EnableDataDump
rootLogLevel@RootLogLevel
expectedProcessStatus@ExpectedProcessStatus
Instances the test binds@ProvidedInstance for built instances, @ProvidedType for classes
extends AbstractDatabaseTest@GenesisDatabaseTest, and @Inject the database as SyncEntityDb, RxEntityDb or AsyncEntityDb, or as SyncDb, RxDb or AsyncDb if the test works with DbRecord and table names
rxDb (on AbstractGenesisTestSupport)@Inject the database, as on the extends AbstractDatabaseTest row, with the same choice of types
createMockDictionary() returning an inline dictionary@ProvidedDictionary with providedDictionary { }
XML dictionary@EnableLegacyXmlDictionary

The database types in the extends AbstractDatabaseTest row are in these packages:

TypePackage
SyncEntityDbglobal.genesis.db.rx.entity.multi
RxEntityDbglobal.genesis.db.rx.entity.multi
AsyncEntityDbglobal.genesis.db.rx.entity.multi
SyncDbglobal.genesis.db
RxDbglobal.genesis.db.rx
AsyncDbglobal.genesis.db

The mapping is by purpose: check each converted test, because the two APIs don't behave identically in every detail. For example, data dump is on by default in the legacy API and off by default in GenesisJunit. Some legacy dictionary set-ups have no GenesisJunit equivalent: a dictionary loaded from an explicit file path, the production dictionary filtered to some tables, and swapping the dictionary in the middle of a test. Keep those tests on the legacy classes, which still compile and run.

Sending messages in a GenesisJunit test​

Inject a GenesisMessageClient into a @GenesisTest class, and use it where a legacy test called sendMessage or sendMessageAsync. The client is connected to the service the test starts. Build the request as a GenesisSet, as in a legacy test, and pass it to sendReqRep with a callback that receives the reply:

import global.genesis.commons.model.GenesisSet
import global.genesis.net.GenesisMessageClient
import global.genesis.testsupport.jupiter.GenesisTest
import jakarta.inject.Inject
import org.junit.jupiter.api.Test
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit

@GenesisTest
class SendMessageTest {

@Inject
lateinit var messageClient: GenesisMessageClient

@Test
fun sendsRequest() {
val set = GenesisSet()
set.setString("MESSAGE_TYPE", "EVENT_MY_EVENT")
// set the other fields the event handler expects

val future = CompletableFuture<GenesisSet>()
messageClient.sendReqRep(set) { reply -> future.complete(reply) }

val reply = future.get(10, TimeUnit.SECONDS)
// assert on the reply GenesisSet here
}
}

sendReqRep has an overload that takes a timeout in seconds as a third argument, sendReqRep(set, consumer, reqRepTimeout). sendReqRep does not wait for the reply, and it does not throw when the client is not connected: it logs an error and the reply never arrives, which is why the test waits on the future with a timeout. To send a message without waiting for a reply, call sendMessage(set). It returns false if the client is not connected.

Database and service tests​

Two types of test are included in the platform:

  • database test (AbstractDatabaseTest)
  • service test (AbstractGenesisTestSupport and GenesisTestSupport)

For both types, you need to start with a dictionary. This section will guide you through using GPAL dictionaries in Genesis tests.

note

As of Genesis 5.2, a sample test case that uses production dictionary will be created automatically when a new project is generated.

Types of dictionary​

There are three types of dictionary you can use:

  • Production dictionary
  • Inline dictionary
  • File dictionary

Production dictionary​

Use this type of dictionary if you want to test against the production dictionary. This is the preferred way of using a dictionary in product tests, as production and test dictionaries are always in sync.

This dictionary type is easiest to use, and it is supported in both Java and Kotlin. When writing a test extending AbstractGenesisTestSupport, the production dictionary is used by default, as it is for GenesisJunit tests, which load the application's dictionary unless you opt out with @EnableLegacyXmlDictionary. To use it from an AbstractDatabaseTest class, is a couple of lines of code:

override fun createMockDictionary(): GenesisDictionary = prodDictionary()

GenesisJunit has no equivalent for filtering the production dictionary to some tables; keep tests that do on the legacy classes (see Mapping to GenesisJunit).

Inline dictionary​

When writing a test in Kotlin, you can use Genesis GPAL syntax to define a dictionary inline. Use this type of dictionary if the dictionary you want to use in your tests is different from the production dictionary. This dictionary should only be used in framework-type components where you want to test dictionaries that are distinct from your production dictionary.

val USER_NAME by field(name = "USER_NAME", type = STRING)
val AGE by field(name = "AGE", type = INT)

override fun createMockDictionary(): GenesisDictionary = testDictionary {
table(name = "USER", id = 1) {
USER_NAME
AGE
primaryKey {
USER_NAME
}
}
}
important

Please note that the table definitions should be valid. If you specify an invalid table, e.g. by not defining a primary key, the test will fail.

In GenesisJunit, use @ProvidedDictionary instead.

File dictionary​

GenesisJunit has no equivalent for a dictionary loaded from a file path; keep tests that use one on the legacy classes (see Mapping to GenesisJunit).

Only use a File dictionary if the dictionary you want to test is:

  • different from the production dictionary
  • too big to be practical in an inline dictionary

Please note that the test will need to resolve the absolute location of the dictionary file, for example:

@Override
protected GenesisDictionary createMockDictionary() throws Exception {
return TestUtil.getDictionaryFromPath(Paths.get(this.getClass().getResource("/DeleteDependentRecords/Dictionaries/KeyIsIntAndString-dictionary.xml").toURI()).toString());
}

In AbstractDatabaseTest, you can also overwrite the dictionaryName() method:

@Override
protected String dictionaryName() {
return "/dictionaries/standard-dictionary.xml";
}

Writing tests​

There two types of test described here:

  • Database tests - use this type for testing classes that require database access.
  • Test support tests - use this type of test for testing a service.

Both types of test work with all three dictionary types.

AbstractDatabaseTest​

Deprecated

AbstractDatabaseTest is deprecated in 10.0 and marked for removal in a future release. Write database tests with @GenesisDatabaseTest instead.

Use this for testing classes that require database access. These tests will instantiate an RxDb object, with a dictionary. The full range of database operations are available, including the update queue. However, no other Genesis components are provided. The only requirement for this type of test is a dictionary.

To write a database test, begin by extending AbstractDatabaseTest, and overwrite the createMockDictionary method, as in the samples below. prodDictionary(), testDictionary { } and field are inherited from the base class, so they need no import.

In the first instance, we are using a production directory.

  • in Kotlin, through the rxDb property
  • in Java, using the getRxDb() method

The test makes sure there are no records in the USER table, then inserts a record and reads it back. In both languages, the RxDb is available. Java builds the record with the DbRecord constructor and plain setters and getters, where Kotlin uses the dbRecord { } builder.

import global.genesis.db.DbRecord.Companion.dbRecord
import global.genesis.db.util.AbstractDatabaseTest

class SampleKotlinTest : AbstractDatabaseTest() {

override fun createMockDictionary(): GenesisDictionary = prodDictionary()

@Test
fun `test count`() {
assert(rxDb.count("USER").blockingGet() == 0L)
}

@Test
fun `test insert and get`() {
rxDb.insert(dbRecord("USER") { setString("USER_NAME", "JohnDoe") }).blockingGet()
val found = rxDb.get(dbRecord("USER") { setString("USER_NAME", "JohnDoe") }, "USER_BY_NAME").blockingGet()
assert(found.getString("USER_NAME") == "JohnDoe")
}
}

When you move a Java test like this to GenesisJunit and inject a SyncDb, the lookup with an index needs all three arguments, because SyncDb.get has no shorter Java overloads. Pass an empty set for the fields:

import global.genesis.db.SyncDb;
import java.util.Collections;

DbRecord found = db.get(key, "USER_BY_NAME", Collections.emptySet());

Here is a similar test using an inline dictionary.

In this test, we define two fields and a table that uses these. We make sure there are no records in the USER table. Since we are creating a stand-alone dictionary, we can start with id 1.

import global.genesis.db.util.AbstractDatabaseTest

class SampleKotlinTest : AbstractDatabaseTest() {

val USER_NAME by field(name = "USER_NAME", type = STRING)
val AGE by field(name = "AGE", type = INT)

override fun createMockDictionary(): GenesisDictionary = testDictionary {
table(name = "USER", id = 1) {
USER_NAME
AGE
primaryKey {
USER_NAME
}
}
}

@Test
fun `test count`() {
assert(rxDb.count("USER").blockingGet() == 0L)
}
}

Finally, here is a test using a file dictionary.

In this test, the dictionary is read from an external file.

In all other regards, the database tests are normal JUnit tests. If you need additional components, you need to construct them or mock them. You won’t be able to specify a GENESIS_HOME folder for additional configuration.

If you add the genesis-generated-dao jar to your classpath, you will be able to use repository classes as normal.

import global.genesis.db.util.AbstractDatabaseTest

class SampleKotlinTest : AbstractDatabaseTest() {

override fun dictionaryName() = "/genesisHome/genesis/cfg/genesis-dictionary.xml"

@Test
fun `test count`() {
assert(rxDb.count("USER").blockingGet() == 0L)
}
}

AbstractGenesisTestSupport​

Deprecated

AbstractGenesisTestSupport is deprecated in 10.0. Use @GenesisTest or @GenesisSharedContextTest instead, adding @PackageScan, @ProvidedInstance, @TestScriptFile and @TestConfigFile as the test requires.

This is a more powerful type of test. In addition to setting up the database, it offers:

  • start-up of a Genesis service in memory
  • scanning of a GENESIS_HOME folder for additional configuration
  • injection of other components directly into the test
  • mock auth-perms
  • asynchronous message handling with timeout and parsing
  • the in-memory database, as the rxDb property (an RxDb), for loading data and asserting on database state

To create a test, you need to provide a GenesisTestConfig instance in the constructor:

PropertyRequiredSets
packageNameyescorresponds to the tag in processes.xml. Setting it more than once appends to packageNames rather than replacing the earlier value
packageNamesnoMutableList<String> of packages, for tests that scan more than one. In Java, use setPackageNames(List<String>) or call addPackageName repeatedly
genesisHomeyesGENESIS_HOME folder for additional configuration
parseryesfunction that takes a GenesisSet and transforms it, this will determine the generic type of AbstractGenesisTestSupport
initialDataFilenocsv files to load into the database
configFileNamenocorresponds to the tag in processes.xml
scriptFileNamenoString?: the GPAL script file under test. Not needed for compiled GPAL definitions
authCacheOverridenooverrides auth-perms map to test; with AbstractGenesisTestSupport, grant access with inMemoryTestAuthCache.authorise(map, entity, user) (from Java, getInMemoryTestAuthCache().authorise(...)) (see Testing with authorization)
dataDumpOnnoBoolean, defaults to true: whether the DATADUMP log level is active in the test
rootLogLevelnoLevel (org.slf4j.event.Level), defaults to INFO: the root log level for the test

Any path provided for genesisHome and initialDataFile must be an absolute location on the test classpath, for example /genesisHome for a folder at src/test/resources/genesisHome.

Tests can also use compiled GPAL definitions (classes extending GPalDataserver, GPalEventHandler, and so on) by ensuring the definition's package is scanned (e.g. by providing an instance of the definition class). In that case no script file or scriptFileName is required.

To use AbstractGenesisTestSupport, create a new class and extend:

import global.genesis.testsupport.AbstractGenesisTestSupport
import global.genesis.testsupport.EventResponse
import global.genesis.testsupport.GenesisTestConfig
import org.junit.jupiter.api.Test

class UserControllerTest : AbstractGenesisTestSupport<EventResponse>(
GenesisTestConfig {
packageName = "global.genesis.auth.manager"
genesisHome = "/genesisHome"
initialDataFile = "standard-user-setup.csv"
authCacheOverride = "USER_VISIBILITY"
parser = EventResponse
configFileName = "config.xml"
scriptFileName = "auth-manager-eventhandler.kts"
}
) {
@Test
fun initialDataIsLoaded() {
// rxDb is provided by AbstractGenesisTestSupport
assert(rxDb.count("USER").blockingGet() > 0L)
}
}

Parsing messages​

AbstractGenesisTestSupport tests require a parser. This should take a GenesisSet and transform it.

This is so that all logic dealing with reading values in these messages is in a single place, and that this can be dealt with by the test support class, so that it can return a type-safe object for the test to verify.

EventResponse is provided as an option. This parses messages into either an EventResponse.Ack or an EventResponse.Nack. The Ack does not hold a lot of data, but the Nack will provide errorCode and text properties to test failure conditions.

It is recommended that the response type is a sealed class in Kotlin with a companion object that implements (GenesisSet) -> xxx, where xxx is your sealed class.

sealed class LoginResponse {
data class LoginAuthAck(
val sessionAuthToken: String,
val refreshAuthToken: String,
val sessionId: String,
val userName: String,
val daysToPasswordExpiry: Int?,
val notifyExpiry: Int?
) : LoginResponse()

data class LoginAuthNack(
val errorCode: AuthFailure,
val text: String
) : LoginResponse()

data class LogoutNack(val errorCode: AuthFailure) : LoginResponse()
object LogoutAck : LoginResponse()
object Other : LoginResponse()

companion object : (GenesisSet) -> LoginResponse {
override fun invoke(genesisSet: GenesisSet): LoginResponse =
when (genesisSet.getString("MESSAGE_TYPE")) {
"EVENT_LOGIN_AUTH_ACK" -> LoginAuthAck(
sessionAuthToken = genesisSet.getString("SESSION_AUTH_TOKEN")!!,
refreshAuthToken = genesisSet.getString("REFRESH_AUTH_TOKEN")!!,
sessionId = genesisSet.getString("SESSION_ID")!!,
userName = genesisSet.getString("USER_NAME")!!,
daysToPasswordExpiry = genesisSet.getInteger("DETAILS.DAYS_TO_PASSWORD_EXPIRY"),
notifyExpiry = genesisSet.getInteger("DETAILS.NOTIFY_EXPIRY")
)
"EVENT_LOGIN_AUTH_NACK" -> {
val firstError = genesisSet.getArray<GenesisSet>("ERROR")!!
.filterNotNull()
.first()

LoginAuthNack(
errorCode = AuthFailure.valueOf(firstError.getString("CODE")!!),
text = firstError.getString("TEXT", "NOT_SET")
)
}
"LOGOUT_ACK" -> LogoutAck
"LOGOUT_NACK" -> LogoutNack(
AuthFailure.valueOf(genesisSet.getString("CODE")!!)
)
else -> Other
}
}
}

Having this parsing logic outside your tests cases makes these a lot simpler to write. For example, using the sealed class and parser above, testing the logging in and logging out again, becomes very simple:

@Test
fun `test logout - success`() {
val message = sendMessage(buildLoginSet()) // build login request
.blockingGet() // await response
.assertedCast<LoginResponse.LoginAuthAck>() // assert message is LoginAuthNack

sendMessage(buildLogoutSet(message.sessionId)) // build logout request with
// provided session id
.blockingGet() // await response
.assertedCast<LoginResponse.LogoutAck>() // assert message is LogoutAck
}

@Test
fun `test logout - failure on session not found`() {
val message = sendMessage(buildLogoutSet("invalid...")) // send logout request
// with invalid id
.blockingGet()
.assertedCast<LoginResponse.LogoutNack>()

assert(message.errorCode == AuthFailure.SESSION_NOT_FOUND)
}

buildLoginSet and buildLogoutSet supporting functions

private fun buildLoginSet(overrides: GenesisSet.() -> Unit = {}): GenesisSet {
val set = GenesisSet()
set.setString("MESSAGE_TYPE", "EVENT_LOGIN_AUTH")
set.setDirect("DETAILS.USER_NAME", USER_NAME)
set.setDirect("DETAILS.PASSWORD", "genesis")
set.overrides()
return set
}

private fun buildLogoutSet(sessionId: String): GenesisSet {
val set = GenesisSet()
set.setString("USER_NAME", USER_NAME)
set.setString("SESSION_ID", sessionId)
set.setString("MESSAGE_TYPE", "EVENT_LOGOUT")
return set
}

Sending messages​

There are two functions for sending messages to a service:

  • one uses RxJava2 Single
  • the other uses Kotlin coroutines

Whichever one you use shouldn’t make a whole lot of difference in your test.

  • The method sendMessage(…) will return a Single; this will require a call to blockingGet() for every message you’re interested in.
  • sendMessageAsync requires you to wrap your test in a runBlocking { … } block.
@Test
fun `test logon failure - incorrect password (rxjava)`() {
val loginSet = buildLoginSet { setDirect("DETAILS.PASSWORD", "WRONG") }

val message = sendMessage(loginSet)
.blockingGet()
.assertedCast<LoginResponse.LoginAuthNack>()

assert(message.errorCode == AuthFailure.INCORRECT_CREDENTIALS) { message.toString() }
}

@Test
fun `test logon failure - incorrect password (coroutines)`() = runBlocking {
val loginSet = buildLoginSet { setDirect("DETAILS.PASSWORD", "WRONG") }

val message = sendMessageAsync(loginSet)
.assertedCast<LoginResponse.LoginAuthNack>()

assert(message.errorCode == AuthFailure.INCORRECT_CREDENTIALS) { message.toString() }
}

Both functions take a GenesisSet and, optionally, a timeout. If no timeout is provided, it will default to 500. Timeouts are set in milliseconds. Behind the scenes, a call will be made to GenesisMessageClient, which handles source refs and waiting for a response (within the timeout).

Type-safe tests for Request Servers​

Below is an example of writing a type-safe test for a Request Server, using a RequestReplyWorkflow.

RequestReplyWorkflow requires two type parameters.

  • The first is the inbound class.
  • The second is the outbound class.
object CompanyFlow : RequestReplyWorkflow<Company.ById, Company> by requestReplyWorkflowBuilder()

@Test
fun `test req rep`(): Unit = runBlocking {
val request = Company.ById("1")

val reply = sendRequest(CompanyFlow, request)

assertEquals(1, reply.size)
assertEquals("1", reply.first().companyId)
}

Overriding the system definition​

You can override system definition properties in your test class by overriding the systemDefinition() function.

assertedCast​

This extension function can be called on any value with a type parameter. If the value is of that type, it will be cast to that type; if not, the call will fail with an AssertError, and a helpful description.

// message will be LoginResponse; our generic response type
val message = sendMessageAsync(loginSet)

// loginAuthAck will be of type LoginResponse.LoginAuthAck
val loginAuthAck = message
.assertedCast<LoginResponse.LoginAuthAck>()

assertIsAuditedBy​

This function helps assertions related to audit tables. It will check that all fields in the audited record match the audit record.

In the test below:

  • We build a request to insert a user.
  • We then get the user from the database to make sure it exists.
  • Next, we check a USER_ATTRIBUTE row has been created.
  • Finally, we check to make sure a matching row in USER_AUDIT has been created.
@Test
fun `test add users - success`() = runBlocking {
sendMessageAsync(buildUserSet(INSERT_USER))
.assertedCast<EventResponse.Ack>()

val user = userRepo.getByName("test-user")
?: throw IllegalArgumentException("User not found!")

assert(user.userName == "test-user") { user }
assert(user.firstName == "Test") { user }
assert(user.lastName == "User") { user }
assert(user.emailAddress == "test-user@genesis.global") { user }
assert(user.status == "PASSWORD_EXPIRED") { user }

assert(passwordService.passwordIsValid(user, "TestPass123")) { "Password check failed" }

val attributes = attributeRepo.getByUserName(user.userName)
?: throw IllegalArgumentException("Attributes not found!")

assert(attributes.accessType == AccessType.ALL) { attributes }

val userAudit = userAuditRepo.getRangeByUnderlyingId("tuser")
.consumeAsFlow()
.first()

// assert all fields in user match in userAudit
user assertIsAuditedBy userAudit

assert(userAudit.auditEventType == "INSERT_USER") { userAudit.toString() }
assert(userAudit.auditEventUser == "JohnWalsh") { userAudit.toString() }

}