Tests with solana-bankrun
Suggest an editA test suite for a Solana program has to cover every instruction the program exposes, every error it can return, and every account a client could swap for a different one. A bug in a deployed program can let an attacker drain the vault, and those funds are gone, so these cases have to be tested before deployment. That is many small tests, run after every change, and it is practical only if the whole run takes seconds.
Run the suite in-process and keep the real validator for release checks
solana-test-validator is a real validator running in a subprocess, communicating over a real RPC port. Startup takes ten to thirty seconds, and every transaction goes through real slot timing of around 400ms, so a suite takes minutes to run. It is useful right before a release, when you want to verify the full integration including your client-side RPC code.
solana-bankrun wraps solana-program-test, the Rust framework that runs your program's compiled BPF bytecode in-process against an in-memory Bank, so tests run in milliseconds. You can set the chain's clock to any time, set account state directly, and inspect outcomes through the same Anchor client SDK production code uses. It is the tool this course uses.
The diagram lists two more tools. LiteSVM is a similar in-process VM with a thinner runtime that often runs faster, but some sysvars are partially implemented. Mollusk is a single-instruction tester written in Rust, used for native Solana programs, meaning non-Anchor ones, and for fuzz testing.
A bankrun test is client code with a different provider
Here's a test file for the counter program whose increment handler is listed in errors and events. It sets up a context, creates counters through initialize, and checks that increment rejects an admin who passes another admin's counter.
import { startAnchor, Clock, ProgramTestContext } from "solana-bankrun";
import { BankrunProvider } from "anchor-bankrun";
import { Program, BN } from "@coral-xyz/anchor";
import { Keypair, LAMPORTS_PER_SOL, PublicKey, SystemProgram } from "@solana/web3.js";
import { expect } from "chai";
import { Counter } from "../target/types/counter";
import IDL from "../target/idl/counter.json";
describe("counter", () => {
let context: ProgramTestContext;
let program: Program<Counter>;
const counterPda = (admin: PublicKey) =>
PublicKey.findProgramAddressSync(
[Buffer.from("counter"), admin.toBuffer()],
program.programId,
)[0];
// Fund a new keypair and create its counter with max = 100.
async function newAdmin(): Promise<Keypair> {
const admin = Keypair.generate();
context.setAccount(admin.publicKey, {
lamports: 10 * LAMPORTS_PER_SOL,
data: Buffer.alloc(0),
owner: SystemProgram.programId,
executable: false,
});
await program.methods
.initialize(new BN(100))
.accounts({ admin: admin.publicKey })
.signers([admin])
.rpc();
return admin;
}
before(async () => {
context = await startAnchor("./", [], []);
program = new Program<Counter>(IDL as Counter, new BankrunProvider(context));
});
it("initializes a counter", async () => {
const admin = await newAdmin();
const counter = await program.account.counter.fetch(counterPda(admin.publicKey));
expect(counter.value.toNumber()).to.equal(0);
expect(counter.admin.toString()).to.equal(admin.publicKey.toString());
});
it("rejects increment on another admin's counter", async () => {
const alice = await newAdmin();
const bob = await newAdmin();
try {
await program.methods
.increment(new BN(1))
.accountsPartial({ counter: counterPda(bob.publicKey), admin: alice.publicKey })
.signers([alice])
.rpc();
expect.fail("expected the call to fail");
} catch (err: any) {
expect(err.toString()).to.include("Unauthorized");
}
});
});The tests use program.methods.X(...).accounts({...}).signers([...]).rpc(), which is the standard Anchor client SDK call. The same code would work against a real validator without modification. The only difference is the provider underneath, which routes the call through the in-process Bank instead of an RPC connection. increment takes accountsPartial instead of accounts. Because of has_one = admin, Anchor can derive admin from the counter, so .accounts() does not accept that field. In bankrun the derivation fails, because it needs the program's IDL stored on chain, so the test passes admin itself through accountsPartial.
startAnchor("./", [], []) finds your Anchor.toml and loads the compiled program from target/deploy into an in-process Bank. It does not build the program. context.setAccount is the direct state-write call. You give it a pubkey and the account data you want at that address, and the simulated chain stores it. Here it funds each admin with 10 SOL, which pays the rent for its counter, with no airdrop and no faucet.
The failure test uses try/catch and asserts on the error message, because that's how Anchor surfaces custom errors to the client side. Each test creates its own admin and counter with newAdmin, so no test depends on state that another test left behind.
Run this with anchor test --skip-build after you've built your program once, and the whole suite finishes in well under a second.
A test can move the clock instead of waiting
The most important feature that bankrun has and solana-test-validator doesn't is control over the chain's clock. You can set the Clock sysvar that your program reads to any time, so logic gated on a future timestamp can be tested without waiting.
Imagine the counter has a lockup feature: once the value hits max, it locks for 24 hours before the admin can reset it. Testing this on a real validator would mean waiting 24 hours. With bankrun, one test checks that an immediate reset fails, and another moves the clock forward and checks that the reset goes through:
async function lockedCounter() {
const admin = await newAdmin();
const counter = counterPda(admin.publicKey);
// Incrementing to max (100) locks the counter.
await program.methods.increment(new BN(100))
.accountsPartial({ counter, admin: admin.publicKey })
.signers([admin]).rpc();
const reset = () => program.methods.reset()
.accountsPartial({ counter, admin: admin.publicKey })
.signers([admin]).rpc();
return { counter, reset };
}
it("rejects a reset right after the counter locks", async () => {
const { reset } = await lockedCounter();
try {
await reset();
expect.fail("expected the reset to fail");
} catch (err: any) {
expect(err.toString()).to.include("StillLocked");
}
});
it("allows a reset 24 hours later", async () => {
const { counter, reset } = await lockedCounter();
// Move the chain's clock forward by 24 hours.
const now = await context.banksClient.getClock();
context.setClock(
new Clock(now.slot, now.epochStartTimestamp, now.epoch,
now.leaderScheduleEpoch, now.unixTimestamp + 86_400n),
);
await reset();
const state = await program.account.counter.fetch(counter);
expect(state.locked).to.be.false;
});context.setClock overwrites the Clock sysvar, so when the handler reads Clock::get()?.unix_timestamp, it sees the time 24 hours later. The whole test runs in milliseconds despite simulating a day passing. The two cases are separate tests because both send the same reset transaction. Inside one test the two copies can get the same blockhash, and the runtime rejects the second as already processed.
context.warpToSlot is not a substitute. It moves the slot number, but a jump of 216,000 slots, about 24 hours at 400ms per slot, moves unix_timestamp by only about seven minutes, so the reset still fails with StillLocked. It also crashes the test process if setAccount added lamports earlier in the run.
The same approach tests vesting contracts that release tokens over a year, staking pools that accrue rewards by the second, timelocks on treasury withdrawals, and subscriptions that expire after thirty days.
One test per scenario, per error, and per swapped account
One assertion path per test. A test that verifies five different things at once tells you nothing useful when it fails. Break out separate tests for the happy path, each error case, and each edge case.
Test the failure cases. Every error variant your program defines should have at least one test that triggers it. The pattern is the try/catch shown above, asserting on the error name in the message. Errors are part of your program's contract with clients, and they break silently if not tested.
Swap every account once. The client chooses every account it passes, so for each account in an instruction's Accounts struct, write one test that puts a different account in that slot and expects the call to fail, unless the instruction is meant to accept any account there. The listing above does this for counter. Alice passes Bob's counter and gets Unauthorized, because that counter stores Bob's key. For admin, the test would sign for Alice's counter with a keypair that is not its admin and expect the same error. The account constraints lesson covers the checks that should reject each swap.
Use setAccount for setup, never for shortcuts. It's tempting to skip writing the initialize call by pre-populating the counter account with the right state. Tests that depend on hand-crafted state can pass even when the initialization logic is broken. Use setAccount only to seed prerequisites your test isn't trying to exercise, like funding keypairs.