Solana 文档LiteSVMRust测试您的程序

快速入门

设置

在测试您的程序之前,请确保您已完成以下步骤:

  1. 构建您的程序以生成 .so 文件
  2. litesvm 作为开发依赖项添加到 Cargo.toml 文件
  3. 添加可能需要的其他开发依赖项,例如 solana-sdklitesvm-token
  4. 在您的 tests 目录中创建测试文件

基本程序测试结构

以下是调用并执行 Solana 程序中某条指令所需的所有基本步骤。

tests/program_test.rs
use litesvm::LiteSVM;
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
};
use my_program;
#[test]
fn test_my_program() {
// Initialize the test environment
let mut svm = LiteSVM::new();
// Deploy your program to the test environment
let program_id = Pubkey::from(my_program::ID);
let program_bytes = include_bytes!("../../../target/deploy/my_program.so");
svm.add_program(program_id, program_bytes);
// Create and fund test accounts
let payer = Keypair::new();
svm.airdrop(&payer.pubkey(), 10_000_000_000).unwrap();
// Create your instruction
let instruction = Instruction {
program_id,
accounts: vec![
AccountMeta::new(payer.pubkey(), true),
],
data: vec![],
};
// Build transaction
let tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer.pubkey()),
&[&payer],
svm.latest_blockhash(),
);
// Send transaction
let result = svm.send_transaction(tx).unwrap();
// Check transaction succeeded
println!("Transaction logs: {:?}", result.logs);
println!("Program executed successfully!");
}

使用 LiteSVM::new() 生成的默认测试环境包含所有已启用的运行时特性、默认系统变量、预编译程序、SPL 程序、签名验证以及所有内置程序,例如 System Program。

如果您希望与默认测试环境中未包含的程序进行交互,则必须将该程序部署到测试环境中。

下一步

在下一节中,我们将详细介绍如何将程序部署到 litesvm 测试环境。

Is this page helpful?

Table of Contents

Edit Page
©️ 2026 Solana 基金会版权所有