Kest

Search

Search the documentation

AI

Testing

Test AI code without a network or a bill.

Real models are slow, cost money and give slightly different answers each time: poor material for unit tests. FakeChatModel returns replies you script and records every request it received, so tests are fast, free and exact.

val model = FakeChatModel.scripted(
    FakeChatModel.call("find_order", mapOf("id" to "1042")),            // first the "model" asks for a tool
    FakeChatModel.text("Order 1042 ships tomorrow."),                  // then it answers
)
val module = Testing.createModule<AppModule> { import(AiModule.forRoot { this.model = model }) }
 
val result = module.get<AiService>().agent().run("Where is order 1042?")
assertEquals("Order 1042 ships tomorrow.", result.text)
assertEquals(1, result.steps.first().toolCalls.size)               // the real @AiTool method ran
assertTrue("1042" in model.requests.last().messages.joinToString { it.content })     // the tool result reached the model

FakeChatModel { request -> ... } computes a reply from the request instead of a fixed script.

What this tests, and what it does not

It tests your code: that the tools work, that prompts contain what they should, that the loop's limits hold, that errors are handled. It does not tell you whether a real model gives good answers. For that:

  • keep a small set of real example questions and run them occasionally (not in the normal build), reading the answers;
  • assert on structure rather than exact wording (the answer mentions the order id; the right tool was called).

Things to test

  • a tool throwing makes the agent recover (script: tool call, then a corrected tool call);
  • the step limit stops a looping model (script endless tool calls and expect stoppedBy);
  • a refusing permission check inside a tool is respected;
  • your prompt building, by asserting on model.requests.

Read more