So I've been attempting to write a unit test for testing an Event in Kotlin, this might help someone (or help contribute to unit testing events here).
build.gradle
:
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.4.10'
id 'application'
id "com.github.johnrengelman.shadow" version "5.2.0"
id 'org.web3j' version '4.8.4'
}
...
dependencies {
implementation "org.web3j:core:$web3jVersion",
"ch.qos.logback:logback-core:$logbackVersion",
"ch.qos.logback:logback-classic:$logbackVersion"
implementation "org.web3j:web3j-unit:$web3jVersion"
implementation "org.web3j:web3j-evm:$web3jVersion"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.3.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.3.1'
}
...
Say I have a contract with the following:
MyContract.sol
:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyContract {
uint public someNumber;
event NumberIncremented(uint someNumber);
constructor() public {
someNumber = 0;
}
function incrementNumber() public {
someNumber = someNumber + 1;
emit NumberIncremented(someNumber);
}
}
MyContractTests.kt
looks like the following:
@EVMTest(NodeType.EMBEDDED)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class MyContractTests {
private lateinit var myContract: MyContract
@BeforeAll
fun deploy(
web3j: Web3j,
transactionManager: TransactionManager,
contractGasProvider: ContractGasProvider
) {
myContract = MyContract.deploy(web3j, transactionManager, contractGasProvider).send()
}
@Test
fun `increment number and emit event`() {
val transactionReceiptVal = myContract.incrementNumber().send()
val response = myContract.getNumberIncrementedEvents(transactionReceiptVal)
Assertions.assertEquals(1, response.size)
}
}
I've tried Greg Jeanmart's method in the unit test, however it seems like using the EmbeddedWeb3JService
throws an UnsupportedOperationException
for eth_filter when using send()
.