Developer docs

Testing plugins with privbot-api-testkit

privbot-api-testkit runs your nodes and services without a game client. You describe the world, run your code, and check two things: what your plugin sent (every action is recorded) and what it concluded (its state, counters and status). The build service runs these tests on every upload (a failing test is reported as TEST.<class>, see Uploading your plugin).

Package: privbot.testkit. Main class: FakeGame.

How it works

FakeGame builds the real PrivContext, every ctx.* facade included, over two fakes: a scripted server adapter and a scripted RuneLite Client. The hooks run their normal code. Only the bottom layer is fake:

your node / service
      |  ctx.inventory.eat("Shark"), ctx.npcs.query()..., ctx.dialogue.select("Yes")
      v
real PrivContext and hooks (privbot.hooks, privbot.query, privbot.wrappers)
      |  reads                                   |  actions
      v                                          v
fake Client  <---- your script ---->   fake adapter -> Dispatch log -> Reactions -> world changes

A green test means your code made the right decisions and sent the right actions, given the world you described. It does not prove a server accepts those actions. In-game behaviour is a separate check.

Add it to a project

Projects made from the template already have it. Otherwise, with the PrivBot plugin parent POM (see PrivBot plugin API: versioning and compatibility):

<dependency>
    <groupId>com.privbot</groupId>
    <artifactId>privbot-api-testkit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <scope>test</scope>
</dependency>
<!-- The client provides Guava at runtime; RuneLite's Text helper needs it in a plain test JVM. -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>23.0</version>
    <scope>test</scope>
</dependency>

The testkit is already a test dependency of your starter project.

A first test

@Test
void eatsWhenLow() {
    try (FakeGame game = FakeGame.builder()
            .hp(8, 30)
            .item(379, "Lobster", item -> item.actions("Eat", null, null, null, "Drop").heals(12))
            .inventory(inv -> inv.add(379, 2))
            .reactions(Reactions.eatHeals())
            .build()) {

        assertTrue(game.ctx().inventory.eat("Lobster"));       // dispatch accepted

        Dispatch eat = game.lastDispatch();                     // what was sent
        assertTrue(eat.is("Eat"));
        assertEquals(379, eat.itemId());

        assertEquals(1, game.inventory().count(379));           // what the world did
        assertEquals(20, game.player().hp());
    }
}

Always close the game: use try-with-resources or close it in @AfterEach.

Describing the world

The builder sets up the start; the same objects change the world during the test.

Area Builder During the test
Local player .player("Name"), .at(x, y[, plane]), .hp(cur, max) game.player().at(..), .hp(..), .heal(n), .damage(n), .animation(id), .moving(true), .inCombat(true), .interacting(npc), .specialAttack(%), .runEnergy(%), .run(true), .overhead(HeadIcon), .die()
Skills game.skills().set(Skill, level), .boost(Skill, current), .xp(..), .gainXp(..)
Item definitions .item(id, name, actions...), .item(id, name, spec) game.items().define(id, name).actions(..).stackable().heals(n).equips(slot)
Inventory .inventory(inv -> inv.add(id, qty)) game.inventory().add/set/remove/clear/fill(..), .unreadable()
Equipment .equipment(worn -> worn.set(EquipmentInventorySlot.WEAPON, id)) game.equipment()...
Bank game.bank().open(), .close(), .items().add(..)
NPCs .npc(id, name, n -> n.at(..)) game.npcs().spawn(id, name, x, y).actions(null, "Attack").hp(cur, max), .dead(), .despawn(), .id(newId)
Other players game.players().spawn(name).combatLevel(..)
Objects game.objects().spawn(id, name, x, y).actions("Chop down"), .remove()
Ground items game.groundItems().drop(id, qty, x, y), stack.remove()
Dialogue game.dialogue().npc(speaker, text), .player(text), .message(text), .options("Yes", "No"), .then(next), .close()
Widgets game.widgets().root(group).child(id).text(..).actions(..).hidden(..), .close(group)
Varps, varbits game.vars().varp(id, v), .varbit(id, v)
Prayers game.prayers().on("Protect from Magic") (the name as the game shows it; case, spaces and underscores do not matter), .off(..)
Login game.logout(), game.login()
Server name .server(ServerType)

Some details that match a real client:

  • Options are positional. actions(null, "Attack") puts Attack second, as on most monsters. An action is sent as that option's position.
  • Hitpoints are a skill. hp(cur, max) sets the boosted and real Hitpoints levels.
  • An unreadable container is not an empty one. inventory().unreadable() makes the client answer "no container". ctx.inventory.snapshot().available is then false. Test that your plugin waits instead of acting.
  • An undefined item has no name. Define every item a test uses.
  • NPC health bars. hp(cur, max) draws a bar; dead() draws an empty one (isDead() is true); an NPC never hit has no bar, and that is not dead.

Dispatches: what your plugin sent

Every action sent through the adapter is recorded as an immutable Dispatch:

Method Meaning
kind() MENU (hook menu actions), AUTOMATED, REPLAY, WALK, PRAYER
option(), target() "Eat", "Attack" / "Goblin", "Take", "Continue"
identifier() NPC index for NPC actions, object id for objects, item id for ground items
actionType() / opcode() the semantic action type (MENU) or the RuneLite MenuAction
param0(), param1() inventory slot / widget id, scene x / scene y, child index / parent widget
itemId() the item an item action carries
walkTarget(), prayer() for walks and prayer toggles
widgetText() the text of the component a widget action addressed ("Yes" for an option choice)
tick(), sequence() when it was sent
is("Eat"), is("Attack", "goblin"), isContinue() matchers

game.dispatched(), game.dispatched("Eat"), game.dispatched(d -> ...), game.lastDispatch() and game.clearDispatched() read the log. FakeGame.INVENTORY_WIDGET, EQUIPMENT_WIDGET and BANK_WIDGET are the widget ids item actions carry. game.sceneToWorld(param0, param1) turns a scene tile back into a world tile.

Reactions: how the world answers

Without a reaction, a dispatch changes nothing, like a server that ignored the click. That is how you test that your plugin checks the result instead of trusting the click:

// No reaction: the eat is accepted and never lands.
game.step(tree.getRunner());
assertEquals(1, game.dispatched("Eat").size());
assertEquals("Eat Lobster did not land", tree.getContext().supplies.status());

Ready-made reactions in Reactions, all installed by .commonReactions():

Reaction Effect
eatHeals() "Eat" removes one item from the dispatched slot and heals by its heals(n)
drinkConsumes() "Drink" removes one item from the dispatched slot
wieldEquips() "Wield", "Wear", "Equip" move the item to its worn slot and swap the old one back
attackEngages() "Attack" puts the player in combat with that NPC or player
takePicksUp() "Take" moves the ground stack into the inventory, if it fits
walkMoves() a walk puts the player on the destination tile
prayerToggles() a prayer toggle flips that prayer
dialogueAdvances() Continue or an option choice closes the dialogue and shows the next then(...) one

Your own:

game.react(Reaction.on(d -> d.is("Chop down"), (g, d) -> g.inventory().add("Logs")).afterTicks(4));
game.react(d -> d.is("Bank"), (g, d) -> g.bank().open());

A reaction that throws fails close(), so a broken script cannot pass silently.

Time

Nothing moves unless the test moves it.

  • game.tick() / game.tick(n) advance the game tick, land reactions that were delayed with afterTicks(n), and run game.onTick(listener) listeners (a scripted NPC, a respawn, a hazard).
  • .autoTick(ms) ticks on a background thread. Use it when a service waits in ctx.sleepUntil for a delayed effect, for example a respawn written as an onTick listener.
  • ctx.objects and ctx.groundItems queries cache once per game tick, as in the client. If a query already ran this tick, call game.tick() after changing the scene.

Running nodes and task trees

Call Does
game.select(runner) which node would run now (every enabled node's shouldExecute, on the client thread)
game.step(runner) select, then execute the winner on the calling thread, as the runner's worker does. Returns the node, or null
game.run(runner, n) n rounds of step + tick. Returns the node names (null for idle rounds)

Build your task tree with game.ctx() and drive its runner. Do not call start(): step stands in for the worker. The example node's test in your starter project drives a task tree this way:

List<String> ran = game.run(tree.getRunner(), 5);
assertEquals(List.of("Eat Food", "Equip Gear", "Loot", "Attack"), ran.subList(0, 4));

Threads

The fake has one client thread. Hooks marshal their reads onto it through GameThread.ensure, as on a RuneLite client. The test thread plays the script worker, so:

  • ctx.sleepUntil(...) works from a test, and refuses on the client thread, as it does in game.
  • node.execute(ctx) and service calls run on the test thread. Use game.step(...) rather than running them inside ctx.read(...) or onClientThread(...).
  • GameThread is static: open one FakeGame at a time per JVM, and close it. Surefire's default (sequential test classes) is right; do not run testkit tests in parallel in one JVM.

Isolation

When the system property privbot.app.root is unset, building a game points it at a temporary directory. PrivBot code your test reaches then never reads or writes your real ~/.privbot. Turn it off with .hermetic(false) only if you set the property yourself.

Not simulated

  • Pathing and travel. ctx.travel.to(...) answers false unless the player is already there. Put travel behind a service you can stub, and test the decision to travel. A walk sent through the adapter is recorded, and walkMoves() applies it.
  • Projectiles, graphics objects, hitsplats and RuneLite events. None are posted. Call your event handlers directly with the event objects.
  • Interfaces you did not build. The bank interface, shops and the spellbook are not drawn; verbs that need them refuse.
  • Server differences. .server(ServerType) changes only what the adapter's server type answers. The fake always behaves like a RuneLite-API client. Per-server support is in What works on each server.
  • Item manager. By default the context has RuneLite's ItemManager backed by the fake item table. .withoutItemManager() models a client without one: inventory names still resolve through the adapter, but ground items report item:<id> names.

Troubleshooting

Symptom Cause
NoClassDefFoundError: Could not initialize class net.runelite.client.util.Text Guava or Commons Text is missing from the test classpath. Add Guava (see above). Commons Text comes with the testkit.
A query does not see an object or ground item you just added The hooks cache the scene per tick: call game.tick().
An item reads as item:385 The item is not defined: game.items().define(385, "Shark").
sleepUntil times out No reaction makes the change, or the reaction is delayed and nothing ticks: use .autoTick(ms) or tick from an onTick listener.
AssertionError from close() A reaction or tick listener threw. The cause is attached.
Wrong node selected game.select(runner) shows the winner. Remember higher priority wins and shouldExecute must be true.