cargo add --dev litesvm solana-sdk@4, cargo add --dev solana-system-interface --features bincode, cargo add --dev solana-transaction-error@3 명령어가 필요합니다
전체 테스트
use litesvm::LiteSVM;
use solana_sdk::{
signature::{Keypair, Signer},
transaction::Transaction,
};
use solana_system_interface::instruction as system_instruction;
use solana_transaction_error::TransactionError;
#[test]
fn test_insufficient_funds_error() {
let mut svm = LiteSVM::new();
let alice = Keypair::new();
let bob = Keypair::new();
// Give Alice only 0.5 SOL
svm.airdrop(&alice.pubkey(), 500_000_000).unwrap();
// Try to transfer 1 SOL (should fail)
let transfer_ix = system_instruction::transfer(
&alice.pubkey(),
&bob.pubkey(),
1_000_000_000, // More than Alice has
);
let tx = Transaction::new_signed_with_payer(
&[transfer_ix],
Some(&alice.pubkey()),
&[&alice],
svm.latest_blockhash(),
);
// Verify it fails with expected error
let result = svm.send_transaction(tx);
assert!(result.is_err());
let err = result.unwrap_err();
match err.err {
TransactionError::InstructionError(0, _) => {
println!("Got expected error: InstructionError (insufficient funds)");
}
_ => panic!("Got unexpected error: {:?}", err.err),
}
// Verify no funds were transferred
assert_eq!(svm.get_balance(&bob.pubkey()).unwrap_or(0), 0);
}
다양한 오류 유형 테스트
유효하지 않은 계정
use solana_sdk::pubkey::Pubkey;
#[test]
fn test_account_not_found() {
let mut svm = LiteSVM::new();
let non_existent = Pubkey::new_unique();
// This should return None
assert!(svm.get_account(&non_existent).is_none());
}
커스텀 프로그램 오류
use solana_sdk::instruction::InstructionError;
use solana_transaction_error::TransactionError;
const YOUR_ERROR_CODE: u32 = 6000; // your program's custom error code
#[test]
fn test_custom_program_error() {
let mut svm = LiteSVM::new();
// Deploy program and trigger custom error
let result = svm.send_transaction(tx);
if let Err(e) = result {
match e.err {
TransactionError::InstructionError(_, InstructionError::Custom(code)) => {
assert_eq!(code, YOUR_ERROR_CODE);
}
_ => panic!("Expected custom error"),
}
}
}
핵심 포인트
- 오류 단언(Assertion):
assert!(result.is_err())를 사용하여 오류가 발생하는지 확인합니다
- 오류 매칭: 특정 오류 유형을 매칭하여 올바른 오류 처리가 이루어지는지
확인합니다
- 상태 검증: 오류가 발생했을 때 상태가 변경되지 않았는지 검증합니다
- 커스텀 오류: 프로그램의 커스텀 오류 코드를 테스트합니다
- 엣지 케이스: 경계 조건과 유효하지 않은 입력을 테스트합니다