🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Solana Testing Deployment Complete Guide

Blockchain DevelopmentđŸŸĸ Free Lesson

Solana Testing Deployment Complete Guide

Testing and deploying Solana programs requires a systematic approach. This guide covers unit tests, integration tests, test validators, and mainnet deployment strategies.

Unit Testing with Anchor

Basic Test Structure

import * as anchor from '@coral-xyz/anchor';
import { Program } from '@coral-xyz/anchor';
import { PublicKey, Keypair, SystemProgram } from '@solana/web3.js';
import { assert } from 'chai';

describe('my-program', () => {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);

  const program = anchor.workspace.MyProgram as Program<MyProgram>;
  const user = Keypair.generate();

  it('Initializes program state', async () => {
    const account = Keypair.generate();
    
    await program.methods
      .initialize(new anchor.BN(100))
      .accounts({
        account: account.publicKey,
        user: provider.wallet.publicKey,
        systemProgram: SystemProgram.programId,
      })
      .signers([account])
      .rpc();

    const accountData = await program.account.myAccount.fetch(account.publicKey);
    assert.equal(accountData.data.toNumber(), 100);
  });

  it('Updates program state', async () => {
    const account = Keypair.generate();
    
    await program.methods
      .initialize(new anchor.BN(100))
      .accounts({
        account: account.publicKey,
        user: provider.wallet.publicKey,
        systemProgram: SystemProgram.programId,
      })
      .signers([account])
      .rpc();

    await program.methods
      .update(new anchor.BN(200))
      .accounts({
        account: account.publicKey,
        user: provider.wallet.publicKey,
      })
      .rpc();

    const accountData = await program.account.myAccount.fetch(account.publicKey);
    assert.equal(accountData.data.toNumber(), 200);
  });
});

Test Assertions

import { expect } from 'chai';

describe('Assertions', () => {
  it('Verifies account data', async () => {
    const account = await program.account.myAccount.fetch(accountPubkey);
    
    // Basic assertions
    expect(account.data.toNumber()).to.equal(100);
    expect(account.owner.toString()).to.equal(userPubkey.toString());
    
    // Boolean assertions
    expect(account.isActive).to.be.true;
    
    // Array assertions
    expect(account.items.length).to.equal(3);
  });

  it('Handles errors correctly', async () => {
    try {
      await program.methods
        .invalidOperation()
        .accounts({ /* ... */ })
        .rpc();
      assert.fail('Should have thrown error');
    } catch (error) {
      expect(error.message).to.contain('Custom error message');
    }
  });
});

Integration Testing

Full Flow Tests

describe('Full Integration Tests', () => {
  let program: Program;
  let provider: anchor.AnchorProvider;
  let user: Keypair;
  let mint: Keypair;

  before(async () => {
    provider = anchor.AnchorProvider.env();
    anchor.setProvider(provider);
    program = anchor.workspace.MyProgram;
    user = Keypair.generate();
    mint = Keypair.generate();

    // Airdrop SOL for testing
    const signature = await provider.connection.requestAirdrop(
      user.publicKey,
      10 * anchor.web3.LAMPORTS_PER_SOL
    );
    await provider.connection.confirmTransaction(signature);
  });

  it('Completes full user flow', async () => {
    // Step 1: Initialize
    const initResult = await program.methods
      .initialize()
      .accounts({
        user: user.publicKey,
        mint: mint.publicKey,
      })
      .signers([user])
      .rpc();
    
    expect(initResult).to.be.a('string');

    // Step 2: Deposit
    await program.methods
      .deposit(new anchor.BN(1000))
      .accounts({
        user: user.publicKey,
        mint: mint.publicKey,
      })
      .signers([user])
      .rpc();

    // Step 3: Verify state
    const account = await program.account.vault.fetch(vaultPda);
    expect(account.balance.toNumber()).to.equal(1000);
  });
});

Cross-Program Testing

describe('Cross-Program Tests', () => {
  it('Calls external program', async () => {
    const externalProgram = await anchor.workspace.ExternalProgram;
    
    await program.methods
      .callExternal(new anchor.BN(100))
      .accounts({
        myProgram: myProgramPda,
        externalProgram: externalProgram.programId,
        externalAccount: externalAccountPda,
      })
      .rpc();
    
    // Verify cross-program state changes
    const externalData = await externalProgram.account.data.fetch(
      externalAccountPda
    );
    expect(externalData.value.toNumber()).to.equal(100);
  });
});

Test Validator

Local Testing Setup

# Start test validator
solana-test-validator

# Or with specific configuration
solana-test-validator \
  --ledger test-ledger \
  --port 8899 \
  --clone EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v \
  --url mainnet-beta

# Deploy to test validator
anchor deploy --provider.cluster localnet

Test Validator Configuration

{
  "extends": "localnet",
  "programs": {
    "localnet": {
      "MyProgram": "MyProgram1111111111111111111111111111111111"
    }
  },
  "accounts": [
    {
      "address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
      "state": {
        "data": "...",
        "owner": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
      }
    }
  ],
  "clone": [
    {
      "address": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
      "url": "https://api.mainnet-beta.solana.com"
    }
  ]
}

Forking Mainnet

# Fork mainnet for testing with real accounts
solana-test-validator \
  --url mainnet-beta \
  --clone EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v \
  --clone 11111111111111111111111111111111 \
  --ledger mainnet-fork

# Access forked validator
solana config set --url localhost:8899

Mock Programs

Creating Mock Programs

use anchor_lang::prelude::*;

declare_id!("MockProgram11111111111111111111111111111111");

#[program]
pub mod mock_program {
    use super::*;

    pub fn mock_transfer(
        ctx: Context<MockTransfer>,
        amount: u64,
    ) -> Result<()> {
        // Simulate token transfer
        msg!("Mock transfer: {} tokens", amount);
        Ok(())
    }

    pub fn mock_swap(
        ctx: Context<MockSwap>,
        amount_in: u64,
        min_amount_out: u64,
    ) -> Result<()> {
        // Simulate swap with price impact
        let amount_out = amount_in * 95 / 100; // 5% slippage
        require!(amount_out >= min_amount_out, ErrorCode::SlippageExceeded);
        msg!("Mock swap: {} -> {}", amount_in, amount_out);
        Ok(())
    }
}

#[derive(Accounts)]
pub struct MockTransfer<'info> {
    #[account(mut)]
    pub from: AccountInfo<'info>,
    #[account(mut)]
    pub to: AccountInfo<'info>,
    pub authority: Signer<'info>,
}

#[derive(Accounts)]
pub struct MockSwap<'info> {
    #[account(mut)]
    pub user: Signer<'info>,
    #[account(mut)]
    pub pool: AccountInfo<'info>,
}

#[error_code]
pub enum ErrorCode {
    #[msg("Slippage exceeded")]
    SlippageExceeded,
}

Using Mocks in Tests

describe('With Mock Programs', () => {
  let mockProgram: Program;

  before(async () => {
    // Deploy mock program
    mockProgram = await anchor.workspace.MockProgram;
  });

  it('Tests with mocked external calls', async () => {
    await program.methods
      .processWithMock(new anchor.BN(100))
      .accounts({
        myProgram: myProgramPda,
        mockProgram: mockProgram.programId,
        mockAccount: mockAccountPda,
      })
      .rpc();
  });
});

Deployment Strategies

Devnet Deployment

# Configure for devnet
solana config set --url devnet

# Create deployment wallet
solana-keygen new -o deploy-keypair.json

# Airdrop SOL
solana airdrop 5 --keypair deploy-keypair.json

# Deploy program
anchor deploy --provider.cluster devnet --program-keypair deploy-keypair.json

# Verify deployment
solana program show <PROGRAM_ID> --url devnet

Mainnet Deployment

# Configure for mainnet
solana config set --url mainnet-beta

# Ensure sufficient SOL
solana balance --keypair deploy-keypair.json

# Deploy with verification
anchor deploy \
  --provider.cluster mainnet-beta \
  --program-keypair deploy-keypair.json \
  --verify

# Set program upgrade authority
solana program set-upgrade-authority \
  <PROGRAM_ID> \
  --keypair deploy-keypair.json \
  --new-upgrade-authority <AUTHORITY_KEYPAIR>

Deployment Checklist

StepCommandVerification
1. Compileanchor buildCheck target/deploy/
2. Verifysolana-verifySignature matches
3. Testanchor testAll tests pass
4. Deployanchor deployProgram deployed
5. Verifysolana program showCorrect owner

CI/CD Pipeline

GitHub Actions Workflow

name: Solana Program CI/CD

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          
      - name: Install Solana CLI
        run: |
          sh -c "$(curl -sSfL https://release.solana.com/v1.17.0)"
          echo "$HOME/.local/share/solana/install/active_release/bin" >> $GITHUB_PATH
          
      - name: Install Anchor
        run: cargo install --git https://github.com/coral-xyz/anchor avm --locked
        avm install latest
        avm use latest
        
      - name: Build
        run: anchor build
        
      - name: Test
        run: anchor test
        
      - name: Deploy to Devnet
        if: github.ref == 'refs/heads/main'
        run: |
          anchor deploy --provider.cluster devnet
        env:
          ANCHOR_WALLET: ${{ secrets.ANCHOR_WALLET }}
          ANCHOR_PROVIDER_URL: https://api.devnet.solana.com

Deployment Automation

// scripts/deploy.ts
import * as anchor from '@coral-xyz/anchor';
import { Program } from '@coral-xyz/anchor';
import { PublicKey, Keypair } from '@solana/web3.js';
import * as fs from 'fs';

async function deploy() {
  const provider = anchor.AnchorProvider.env();
  anchor.setProvider(provider);

  // Load program keypair
  const programKeypair = Keypair.fromSecretKey(
    Buffer.from(JSON.parse(fs.readFileSync('deploy-keypair.json', 'utf-8')))
  );

  // Deploy
  const program = anchor.workspace.MyProgram as Program<any>;
  
  console.log('Program ID:', program.programId.toString());
  console.log('Deploying to:', provider.connection.rpcEndpoint);

  // Verify deployment
  const accountInfo = await provider.connection.getAccountInfo(program.programId);
  if (accountInfo) {
    console.log('Program deployed successfully');
  } else {
    throw new Error('Deployment failed');
  }
}

deploy().catch(console.error);

Performance Testing

Load Testing

describe('Performance Tests', () => {
  it('Handles concurrent transactions', async () => {
    const transactions = [];
    const users = Array(10).fill(null).map(() => Keypair.generate());

    // Create concurrent transactions
    for (const user of users) {
      const tx = program.methods
        .initialize()
        .accounts({
          user: user.publicKey,
          account: Keypair.generate().publicKey,
        })
        .signers([user])
        .rpc();
      
      transactions.push(tx);
    }

    // Execute concurrently
    const results = await Promise.all(transactions);
    expect(results.length).to.equal(10);
  });

  it('Measures transaction latency', async () => {
    const start = Date.now();
    
    await program.methods
      .initialize()
      .accounts({ /* ... */ })
      .rpc();
    
    const latency = Date.now() - start;
    expect(latency).to.be.lessThan(5000); // Under 5 seconds
  });
});

Stress Testing

describe('Stress Tests', () => {
  it('Handles large batch operations', async () => {
    const batchSize = 100;
    const items = Array(batchSize).fill(null).map((_, i) => ({
      id: i,
      amount: new anchor.BN(i * 100),
    }));

    await program.methods
      .batchProcess(items)
      .accounts({ /* ... */ })
      .rpc();

    const account = await program.account.batchAccount.fetch(batchPda);
    expect(account.processedCount.toNumber()).to.equal(batchSize);
  });
});

Troubleshooting

Common Test Issues

IssueCauseSolution
Transaction timeoutNetwork congestionIncrease commitment level
Account not foundWrong PDA derivationVerify seeds and bumps
Insufficient SOLNot enough for feesAirdrop more SOL
Program not foundWrong clusterCheck solana config
Signature mismatchWrong keypairVerify keypair paths

Debug Logging

// Enable debug logging
process.env.ANCHOR_LOG = 'debug';

// Custom logging in tests
beforeEach(function () {
  console.log(`Running: ${this.currentTest.title}`);
});

afterEach(function () {
  if (this.currentTest.state === 'failed') {
    console.log(`Failed: ${this.currentTest.err?.message}`);
  }
});

Trade-offs

Testing Trade-offs

DecisionCoverageSpeedCost
Unit testsHighFastLow
Integration testsHighSlowMedium
E2E testsCompleteVery slowHigh
Mock testsPartialFastLow
Mainnet testsRealisticVariableHigh

Deployment Trade-offs

FactorDevnetTestnetMainnet
CostFreeFreeReal SOL
SpeedFastFastVariable
RiskNoneLowHigh
ValidationLimitedGoodFull
RollbackEasyEasyHard

Interview Questions

  1. What is the difference between unit tests and integration tests for Solana programs?

  2. How do you test cross-program interactions?

  3. Explain the deployment process from devnet to mainnet.

Quiz Questions

  1. What command starts a local test validator?

    • a) solana start
    • b) solana-test-validator
    • c) anchor start
    • d) anchor test
  2. Why is forking mainnet useful for testing?

    • a) Faster execution
    • b) Real account data
    • c) Lower costs
    • d) Better security
  3. What should be verified before mainnet deployment?

    • a) Code style
    • b) Test coverage
    • c) Developer experience
    • d) Documentation

Conclusion

Testing and deploying Solana programs requires careful planning and execution. Comprehensive testing with unit tests, integration tests, and test validators ensures program reliability before mainnet deployment.

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-09-22

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement