diff --git a/sorting/Cargo.toml b/sorting/Cargo.toml index ad267b1..6fbfa0d 100644 --- a/sorting/Cargo.toml +++ b/sorting/Cargo.toml @@ -6,4 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -rand = "0.8.4" \ No newline at end of file +rand = "0.8.4" + +[dev-dependencies] +test-case = "1.2.1" \ No newline at end of file diff --git a/sorting/src/lib.rs b/sorting/src/lib.rs index 654d2cc..28a127f 100644 --- a/sorting/src/lib.rs +++ b/sorting/src/lib.rs @@ -1,5 +1,5 @@ pub mod bubble_sort { - pub fn sort(vec: &mut Vec) { + pub fn sort(vec: &mut Vec) { for outer in (0..vec.len()).rev() { for inner in 0..outer { if vec[inner] > vec[inner + 1] { @@ -10,7 +10,7 @@ pub mod bubble_sort { } } -fn swap(vec: &mut Vec, index_one: usize, index_two: usize) { +fn swap(vec: &mut Vec, index_one: usize, index_two: usize) { let temp = vec[index_two]; vec[index_two] = vec[index_one]; vec[index_one] = temp; @@ -19,17 +19,17 @@ fn swap(vec: &mut Vec, index_one: usize, index_two: usize) { #[cfg(test)] mod lib_tests { use super::*; + use std::fmt::Debug; + use test_case::test_case; - #[test] - fn can_swap_numbers() { - // Arrange - let mut vec = vec![1, 2]; - + #[test_case(vec ! [1, 2], vec ! [2, 1]; "integers")] + #[test_case(vec ! ["hello", "world"], vec ! ["world", "hello"]; "strings")] + #[test_case(vec ! [5.0, 10.0], vec ! [10.0, 5.0]; "floats")] + fn can_swap(mut actual: Vec, expected: Vec) { // Act - swap(&mut vec, 0, 1); + swap(&mut actual, 0, 1); // Assert - assert_eq!(vec[0], 2); - assert_eq!(vec[1], 1); + assert_eq!(actual, expected); } } \ No newline at end of file diff --git a/sorting/tests/integration_tests.rs b/sorting/tests/integration_tests.rs index 0bc3e39..11dd016 100644 --- a/sorting/tests/integration_tests.rs +++ b/sorting/tests/integration_tests.rs @@ -1,18 +1,22 @@ -use rand::seq::SliceRandom; +use std::fmt::Debug; +use rand::{ + seq::SliceRandom, + thread_rng +}; use sorting; -use rand::thread_rng; +use test_case::test_case; +use sorting::bubble_sort::sort; -#[test] -fn bubble_sort_ascending() { +#[test_case((0..20).rev().collect(), (0..20).collect() ; "integers")] +#[test_case(vec!["c", "b", "a"], vec!["a", "b", "c"] ; "strings")] +#[test_case(vec![6.0, 10.0, 2.0, 4.0, 8.0], vec![2.0, 4.0, 6.0, 8.0, 10.0] ; "floats")] +fn can_bubble_sort(mut actual: Vec, expected: Vec) { // Arrange - let mut vec: Vec = (0..20).rev().collect(); - vec.shuffle(&mut thread_rng()); + actual.shuffle(&mut thread_rng()); // Act - sorting::bubble_sort::sort(&mut vec); + sort(&mut actual); // Assert - for i in 0..20 { - assert_eq!(vec[i], i); - } + assert_eq!(actual, expected); } \ No newline at end of file