Chapter 7: Advanced Testing

Comprehensive testing is crucial for production code. This chapter covers advanced testing techniques including property testing, fuzzing, mocking, and more.

7.1 Unit Testing Best Practices

Organizing Tests

// src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add_positive() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    fn test_add_negative() {
        assert_eq!(add(-2, -3), -5);
    }

    #[test]
    #[should_panic(expected = "overflow")]
    fn test_add_overflow() {
        add(i32::MAX, 1);
    }

    #[test]
    #[ignore]
    fn expensive_test() {
        // This test is ignored by default
        // Run with: cargo test -- --ignored
    }
}

// tests/integration_test.rs
#[test]
fn integration_test() {
    // Integration tests go in separate files
}

Custom Test Assertions

macro_rules! assert_approx_eq {
    ($a:expr, $b:expr, $epsilon:expr) => {
        let diff = ($a - $b).abs();
        assert!(
            diff < $epsilon,
            "assertion failed: {} ≈ {} (diff: {})",
            $a, $b, diff
        );
    };
}

#[test]
fn test_floating_point() {
    assert_approx_eq!(0.1 + 0.2, 0.3, 1e-10);
}

// Using more_asserts crate
use more_asserts::{assert_gt, assert_le};

#[test]
fn test_ordering() {
    assert_gt!(5, 3);
    assert_le!(2, 5);
}

7.2 Property-Based Testing

Property-based testing generates random inputs to verify properties that should always hold:

use proptest::prelude::*;

fn reverse<T: Clone>(vec: &[T]) -> Vec<T> {
    vec.iter().rev().cloned().collect()
}

proptest! {
    #[test]
    fn test_reverse_twice_is_identity(vec in prop::collection::vec(any::<i32>(), 0..100)) {
        let reversed_twice = reverse(&reverse(&vec));
        prop_assert_eq!(vec, reversed_twice);
    }

    #[test]
    fn test_reverse_length(vec in prop::collection::vec(any::<i32>(), 0..100)) {
        let reversed = reverse(&vec);
        prop_assert_eq!(vec.len(), reversed.len());
    }

    #[test]
    fn test_addition_commutative(a in any::<i32>(), b in any::<i32>()) {
        prop_assume!(a.checked_add(b).is_some()); // Avoid overflow
        prop_assert_eq!(a + b, b + a);
    }
}

Custom Generators

use proptest::prelude::*;

#[derive(Debug, Clone)]
struct User {
    name: String,
    age: u8,
    email: String,
}

fn user_strategy() -> impl Strategy<Value = User> {
    (
        "[a-z]{3,10}",           // name: 3-10 lowercase letters
        1u8..100,                // age: 1-99
        "[a-z]{5,10}@[a-z]{3,7}\\.com",  // email
    )
        .prop_map(|(name, age, email)| User { name, age, email })
}

proptest! {
    #[test]
    fn test_user_age_valid(user in user_strategy()) {
        prop_assert!(user.age > 0 && user.age < 100);
    }

    #[test]
    fn test_user_email_format(user in user_strategy()) {
        prop_assert!(user.email.contains('@'));
        prop_assert!(user.email.ends_with(".com"));
    }
}

7.3 Fuzzing

Fuzzing automatically generates inputs to find crashes and bugs:

// Install: cargo install cargo-fuzz
// Create fuzzer: cargo fuzz init

// fuzz/fuzz_targets/fuzz_parser.rs
#![no_main]
use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    if let Ok(s) = std::str::from_utf8(data) {
        // Fuzz your parser
        let _ = my_parser::parse(s);
    }
});

// Run: cargo fuzz run fuzz_parser

// Structured fuzzing with arbitrary
use arbitrary::Arbitrary;

#[derive(Debug, Arbitrary)]
struct FuzzInput {
    action: Action,
    value: i32,
}

#[derive(Debug, Arbitrary)]
enum Action {
    Add,
    Subtract,
    Multiply,
}

fuzz_target!(|input: FuzzInput| {
    match input.action {
        Action::Add => { /* test add */ }
        Action::Subtract => { /* test subtract */ }
        Action::Multiply => { /* test multiply */ }
    }
});

7.4 Mocking and Test Doubles

Manual Mocking

trait Database {
    fn get_user(&self, id: u64) -> Option<String>;
    fn save_user(&mut self, id: u64, name: String) -> Result<(), String>;
}

struct MockDatabase {
    users: std::collections::HashMap<u64, String>,
}

impl Database for MockDatabase {
    fn get_user(&self, id: u64) -> Option<String> {
        self.users.get(&id).cloned()
    }

    fn save_user(&mut self, id: u64, name: String) -> Result<(), String> {
        self.users.insert(id, name);
        Ok(())
    }
}

#[test]
fn test_user_service() {
    let mut db = MockDatabase {
        users: std::collections::HashMap::new(),
    };

    db.save_user(1, "Alice".to_string()).unwrap();
    assert_eq!(db.get_user(1), Some("Alice".to_string()));
}

Using mockall

use mockall::*;

#[automock]
trait Repository {
    fn find_by_id(&self, id: u64) -> Option<String>;
    fn save(&mut self, id: u64, data: String);
}

#[test]
fn test_with_mock() {
    let mut mock = MockRepository::new();

    // Set expectations
    mock.expect_find_by_id()
        .with(eq(1))
        .times(1)
        .returning(|_| Some("Alice".to_string()));

    mock.expect_save()
        .with(eq(2), eq("Bob".to_string()))
        .times(1)
        .returning(|_, _| ());

    // Use the mock
    assert_eq!(mock.find_by_id(1), Some("Alice".to_string()));
    mock.save(2, "Bob".to_string());
}

7.5 Snapshot Testing

use insta::assert_snapshot;

fn render_user(name: &str, age: u8) -> String {
    format!(
        r#"
        <div class="user">
            <h1>{}</h1>
            <p>Age: {}</p>
        </div>
        "#,
        name, age
    )
}

#[test]
fn test_render_user() {
    let output = render_user("Alice", 30);
    assert_snapshot!(output);
}

// First run creates snapshot
// Subsequent runs compare against it
// Review changes: cargo insta review

7.6 Integration Testing

Testing HTTP APIs

// tests/api_test.rs
use axum::{Router, routing::get};
use tower::ServiceExt;
use http::{Request, StatusCode};

async fn hello() -> &'static str {
    "Hello, World!"
}

fn app() -> Router {
    Router::new().route("/", get(hello))
}

#[tokio::test]
async fn test_hello_endpoint() {
    let app = app();

    let response = app
        .oneshot(Request::builder().uri("/").body(()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);

    let body = hyper::body::to_bytes(response.into_body())
        .await
        .unwrap();
    assert_eq!(&body[..], b"Hello, World!");
}

Database Testing

use sqlx::{PgPool, postgres::PgPoolOptions};

async fn setup_test_db() -> PgPool {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres://localhost/test_db")
        .await
        .unwrap();

    // Run migrations
    sqlx::migrate!("./migrations")
        .run(&pool)
        .await
        .unwrap();

    pool
}

async fn cleanup_test_db(pool: &PgPool) {
    sqlx::query("TRUNCATE TABLE users")
        .execute(pool)
        .await
        .unwrap();
}

#[tokio::test]
async fn test_create_user() {
    let pool = setup_test_db().await;

    sqlx::query("INSERT INTO users (name, email) VALUES ($1, $2)")
        .bind("Alice")
        .bind("alice@example.com")
        .execute(&pool)
        .await
        .unwrap();

    let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM users")
        .fetch_one(&pool)
        .await
        .unwrap();

    assert_eq!(count.0, 1);

    cleanup_test_db(&pool).await;
}

7.7 Performance Testing

Benchmarking with Criterion

use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};

fn fibonacci(n: u64) -> u64 {
    match n {
        0 | 1 => 1,
        n => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

fn criterion_benchmark(c: &mut Criterion) {
    let mut group = c.benchmark_group("fibonacci");

    for i in [10u64, 15, 20].iter() {
        group.bench_with_input(BenchmarkId::from_parameter(i), i, |b, &i| {
            b.iter(|| fibonacci(black_box(i)));
        });
    }

    group.finish();
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);

Load Testing

use tokio::time::{sleep, Duration};
use std::sync::Arc;
use tokio::sync::Semaphore;

#[tokio::test]
async fn load_test_api() {
    let semaphore = Arc::new(Semaphore::new(100)); // Max 100 concurrent
    let mut handles = vec![];

    for i in 0..1000 {
        let permit = semaphore.clone().acquire_owned().await.unwrap();
        let handle = tokio::spawn(async move {
            let _permit = permit; // Hold permit
            // Make request
            let response = make_api_request(i).await;
            assert!(response.is_ok());
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.await.unwrap();
    }
}

async fn make_api_request(id: u64) -> Result<(), String> {
    sleep(Duration::from_millis(10)).await;
    Ok(())
}

7.8 Test Organization

Test Fixtures

struct TestContext {
    db: MockDatabase,
    config: Config,
}

impl TestContext {
    fn new() -> Self {
        TestContext {
            db: MockDatabase::new(),
            config: Config::default(),
        }
    }

    fn with_user(mut self, id: u64, name: &str) -> Self {
        self.db.users.insert(id, name.to_string());
        self
    }
}

#[test]
fn test_with_fixture() {
    let ctx = TestContext::new()
        .with_user(1, "Alice")
        .with_user(2, "Bob");

    assert_eq!(ctx.db.get_user(1), Some("Alice".to_string()));
}

Test Helpers

mod test_helpers {
    pub fn create_test_user(name: &str) -> User {
        User {
            id: 1,
            name: name.to_string(),
            email: format!("{}@example.com", name.to_lowercase()),
        }
    }

    pub fn assert_user_eq(a: &User, b: &User) {
        assert_eq!(a.id, b.id);
        assert_eq!(a.name, b.name);
        assert_eq!(a.email, b.email);
    }
}

#[test]
fn test_user_creation() {
    let user = test_helpers::create_test_user("Alice");
    assert_eq!(user.name, "Alice");
}

7.9 Code Coverage

// Install tarpaulin
// cargo install cargo-tarpaulin

// Run coverage
// cargo tarpaulin --out Html --output-dir coverage

// Or use llvm-cov (built-in)
// rustup component add llvm-tools-preview
// cargo install cargo-llvm-cov

// Run coverage
// cargo llvm-cov --html

// Example: achieving high coverage
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err("Division by zero".to_string())
    } else {
        Ok(a / b)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_divide_success() {
        assert_eq!(divide(10, 2), Ok(5));
    }

    #[test]
    fn test_divide_by_zero() {
        assert_eq!(divide(10, 0), Err("Division by zero".to_string()));
    }

    // 100% coverage achieved!
}

7.10 Chapter Summary

Key Takeaways

Korea Standardization Infrastructure Mapping

Korea operates a comprehensive standards governance system through inter-ministerial cooperation. National Standards Council (under Prime Minister's Office, per Framework Act on National Standards Article 5) coordinates KATS (Korean Agency for Technology and Standards), MFDS (Ministry of Food and Drug Safety), MOTIE (Ministry of Trade, Industry and Energy), MSIT (Ministry of Science and ICT), MOIS (Ministry of the Interior and Safety), MOE (Ministry of Environment), MOHW (Ministry of Health and Welfare), MND (Ministry of National Defense), MCST (Ministry of Culture, Sports and Tourism), MOFA (Ministry of Foreign Affairs), MOJ (Ministry of Justice), and FSC (Financial Services Commission). Accreditation and Testing: KOLAS (Korea Laboratory Accreditation Scheme) accredits 800+ testing laboratories. KAS (Korea Accreditation System) accredits 50+ certification bodies. KTC (Korea Testing Certification), KTR (Korea Testing & Research Institute), KTL (Korea Testing Laboratory), and KCL (Korea Conformity Laboratories) provide conformance testing. Telecom and Cyber: KCC (Korea Communications Commission), KCA (Korea Communications Agency), TTA (Telecommunications Technology Association), IITP (Institute for Information & Communications Technology Planning & Evaluation), NIPA (National IT Industry Promotion Agency), KISA (Korea Internet & Security Agency), KCMVP (Korea Cryptographic Module Validation Program), NIS (National Intelligence Service), NSR (National Security Research Institute), and NCSC (National Cyber Security Center). National R&D Centers: KIST, ETRI, KAIST, Seoul National University, Yonsei University, Korea University, POSTECH, UNIST, GIST, DGIST, KISTI, KIER, KIMM, KRICT, KFRI, KRIBB. International Standards Cooperation: ISO TC/SC Korean secretariats, IEC TC/SC Korean secretariats, ITU-T Study Group Korean chairs, 3GPP RAN/SA Korean chairs, IEEE 802 Korean chairs, W3C Korea office, OASIS Korea office, IETF Korea cooperation, OECD CSTP, UN ESCAP, APEC SCSC Korean cooperation. Korean Industrial Standards (KS) Catalog: KS X (Information) 25,000+, KS A (Basic) 15,000+, KS B (Machinery) 25,000+, KS C (Electrical) 18,000+, KS D (Metallurgy) 12,000+, KS E (Mining) 5,000+, KS F (Construction) 18,000+, KS H (Food) 8,000+, KS I (Environment) 5,000+, KS J (Biology) 3,000+, KS K (Textile) 15,000+, KS L (Ceramics) 7,000+, KS M (Chemistry) 12,000+, KS P (Medical) 5,000+, KS Q (Quality Mgmt) 4,000+, KS R (Transport) 12,000+, KS S (Service) 3,000+, KS T (Packaging) 4,000+, KS V (Shipbuilding) 5,000+, KS W (Aerospace) 3,000+ — totaling 220,000+ Korean Industrial Standards. Key Acts: Personal Information Protection Act (Act 19234, effective Sept 15, 2024), Electronic Government Act, Electronic Signature Act, Act on Promotion of Information and Communications Network Utilization and Information Protection, Information and Communications Infrastructure Protection Act, Data Industry Act, Public Data Act, AI Framework Act (Act 20212, effective July 2026), Industrial Technology Innovation Promotion Act, Framework Act on Science and Technology — 70+ Korean standardization-related laws.

Korea Digital Transformation Detailed Mapping

Korea operates digital transformation through a comprehensive governance system. Digital Government: Digital Platform Government Committee (established September 2022, under the President)·Ministry of the Interior and Safety Digital Government Bureau·e-Government Support Center·Gov.kr·National Citizen Service·KDIS (Korea Digital Information Society)·NIA (National Information Society Agency)·MOIS (Ministry of the Interior and Safety). K-DNS Infrastructure: Korea Internet & Security Agency (KISA) Korea Internet Center·KISA DNS Root Server·KRNIC (Korea Network Information Center)·BGP Korea·National Cyber Security Center (NCSC)·KCC (Korea Communications Commission)·MSIT (Ministry of Science and ICT)·NIA·NIPA. Korean Cloud Infrastructure: KT Cloud·NAVER Cloud (NCloud)·Samsung SDS Cloud·LG U+ Cloud·NHN Cloud·Kakao Enterprise Cloud·SK Telecom Cloud·KISA Cloud Security Assurance Program (CSAP)·KCMVP-validated cloud·ISMS-P (Information Security & Personal Information Management System). Korean Security Certifications: KISA ISMS-P certification·KCMVP (Korean Cryptographic Module Validation Program)·NIS (National Intelligence Service) "National Cryptographic Technology Operation Standards"·NCSC "National Cyber Security Strategy 2024-2028"·CC (Common Criteria) Korean evaluation bodies·EAL4·EAL5·KS X ISO/IEC 15408·19790·24759 Korean Profile. Korean Data Standards: NIA AI Hub·National Data Standardization Committee·Statistics Korea (KOSTAT)·MyData 4 Designated Combination Specialists (Samsung SDS, KICI, KOSTAT, KFTC)·National Institute of Korean Language·National Law Information Center·National Spatial Information Platform·National Spatial Data Center·Korean Spatial Information Standards. Finance and Fintech Standards: FSC (Financial Services Commission)·FSS (Financial Supervisory Service)·FIU (Financial Intelligence Unit)·BOK (Bank of Korea)·FSEC (Financial Security Institute)·KFTC (Korea Financial Telecommunications)·KSD (Korea Securities Depository)·KRX (Korea Exchange) 8-agency cooperation. 5G/6G Communications Infrastructure: 5G subscribers 35 million (2024)·5G base stations 350,000·6G commercialization target 2028·5G dedicated networks 16 operators·6G Acceleration Council (MSIT, 2024). K-Content: KOCCA (Korea Creative Content Agency)·MCST (Ministry of Culture, Sports and Tourism)·KCA (Korea Communications Agency)·Korea Culture Information Service Agency·Korean Film Archive·Korea Publishing Industry Promotion Agency. Data 3 Acts (Personal Information Protection Act·Credit Information Act·Telecommunications Network Act, 2020 enforcement)·Data Industry Act (2021)·Public Data Act (2013)·AI Framework Act (2026)·Digital Platform Government Framework Act (2024 proposed) — Korea digital transformation core legislation.

Korea Industrial, Research, Education Infrastructure Mapping

Korea operates its industrial ecosystem and standardization system through the following core infrastructure. Korea Top 5 Groups: Samsung, Hyundai Motor, LG, SK, Lotte. Each group operates standardization committees and ISO/IEC TC Korean secretariats. Samsung Electronics (semiconductors, displays, home appliances, telecom)·Hyundai Motor (automobiles, mobility)·LG Electronics (home appliances, displays, OLED)·SK hynix (memory)·LG Energy Solution·Samsung SDI (batteries)·POSCO Future M (materials)·Hyundai Mobis (parts). Korean IT Big Tech: NAVER (search, cloud, AI HyperCLOVA)·Kakao (messenger, payment, mobility, banking)·Coupang (e-commerce, logistics)·Karrot Market·Toss·Woowa Brothers. Korea Telcos: SK Telecom·KT·LG U+. 5G·5G dedicated networks·B2B cloud·AI businesses operating. Korea Top 7 Research Universities: Seoul National University·KAIST·POSTECH·Yonsei University·Korea University·UNIST·DGIST·GIST. All serve as standardization R&D bases and ISO/IEC/IEEE Korean chairs. Korea Government-affiliated National Research Institutes (26): KIST, KAERI, KIMM, KIER, KFRI, KRICT, KRIBB, KARI, KASI, KIGAM, KICT, KISTI, KETI, ETRI, NIMS, KIMS, KISDI, KOTRA, STEPI, KOEN, KICCE, KIET, KIPF, KIHASA, KICJ, KLRI. Korea Industrial Complexes / Tech Valleys: Pangyo Techno Valley·Dongtan·Gwanggyo·Songdo IBD·Yeouido·Gangnam·Sihwa·Banwol·Gumi·Ulsan·Changwon·Geoje·Yeosu·Onsan·Cheongju·Iksan·Gwangyang·POSCO Gwangyang Steel Mill·Asan Bay·Seosan·Songdo·Incheon Airport·Sejong·Cheongna·Geomdan. Korea Trade and Finance Infrastructure: Korea International Trade Association (KITA)·Korea Trade-Investment Promotion Agency (KOTRA)·Export-Import Bank of Korea (KEXIM)·Bank of Korea·Kookmin Bank·Shinhan·Hana·Woori·NH Nonghyup·IBK Industrial Bank·SC First Bank·Citi Bank Korea·HSBC Korea·DBS Korea — 14 Korean major banks and foreign banks. Korea K-POP / K-Content: HYBE·SM·YG·JYP 4 major entertainment companies·CJ ENM·tvN·MBC·KBS·SBS·EBS·YTN·Yonhap News TV·JTBC Korean broadcasting·NETFLIX Korea·Disney Plus·TVING·Wavve·Watcha·Coupang Play. Korea Gaming Industry: Nexon·NCsoft·Krafton·Netmarble·Kakao Games·Pearl Abyss·Com2uS·Gamevil·NHN·Smilegate·Webzen. Korea Automotive / Battery: Hyundai Motor·Kia·Genesis·LG Energy Solution·Samsung SDI·SK On·POSCO Future M·EcoPro·L&F battery cathode material suppliers. Korea Semiconductor: Samsung Electronics (HBM3E·HBM4)·SK hynix (HBM3E 12-Hi)·DB HiTek·SK siltron·SK Enpulse·Dongjin Semichem·Seoul Semiconductor·Simmtech·Samsung Display·LG Display.