0 介绍
视频地址:www.bilibili.com/video/BV1eg411g7c...
相关源码:github.com/anonymousGiga/Rust-and-...
本节我们开始测试,我们首先来测试tick函数,以确保提供我们期望的输出。
1 完善Universe
我们在wasm_game_of_life/src/lib.rs中的impl Universe块中创建一些setter和getter函数,代码如下:
impl Universe { | |
... | |
pub fn set_width(&mut self, width: u32) { | |
self.width = width; | |
self.cells = (0..width * self.height).map(|_i| Cell::Dead).collect(); | |
} | |
pub fn set_height(&mut self, height: u32) { | |
self.height = height; | |
self.cells = (0..self.width * height).map(|_i| Cell::Dead).collect(); | |
} | |
pub fn width(&self) -> u32 { | |
self.width | |
} | |
... | |
} |
再添加获取和设置宇宙中细胞状态的代码(注意,以下添加的代码是要重新写一个Universe块,且此块上面是没有#[wasm_bindgen]):
//此处没有#[wasm_bindgen] | |
impl Universe { | |
... | |
pub fn get_cells(&self) -> &[Cell] { | |
&self.cells | |
} | |
pub fn set_cells(&mut self, cells: &[(u32, u32)]) { | |
for (row, col) in cells.iter().cloned() { | |
let idx = self.get_index(row, col); | |
self.cells[idx] = Cell::Alive; | |
} | |
} | |
... | |
} |
2 创建测试程序
2.1 准备测试文件
在wasm-game-of-life文件下,运行如下命令:
wasm-pack test --chrome --headless
通过此命令,我们可以得到一个tests文件夹,里面有一个web.rs文件。上面的命令中,–chrome,你也可以换成–firefox, –safari, 以及–node等任何你想测试的浏览器对应的参数。
2.2 编写测试代码
修改整个web.rs如下:
//! Test suite for the Web and headless browsers. | |
extern crate wasm_bindgen_test; | |
use wasm_bindgen_test::*; | |
extern crate wasm_game_of_life; | |
use wasm_game_of_life::Universe; | |
wasm_bindgen_test_configure!(run_in_browser); | |
fn pass() { | |
assert_eq!(1 + 1, 2); | |
} | |
pub fn input_spaceship() -> Universe { | |
let mut universe = Universe::new(); | |
universe.set_width(6); | |
universe.set_height(6); | |
universe.set_cells(&[(1,2), (2,3), (3,1), (3,2), (3,3)]); | |
universe | |
} | |
pub fn expected_spaceship() -> Universe { | |
let mut universe = Universe::new(); | |
universe.set_width(6); | |
universe.set_height(6); | |
universe.set_cells(&[(2,1), (2,3), (3,2), (3,3), (4,2)]); | |
universe | |
} | |
pub fn test_tick() { | |
let mut input_universe = input_spaceship(); | |
let expected_universe = expected_spaceship(); | |
input_universe.tick(); | |
assert_eq!(&input_universe.get_cells(), &expected_universe.get_cells()); | |
} |
2.3 运行测试
在wasm-game-of-life文件夹下运行如下命令:
wasm-pack test --chrome --headless
运行完成可以看到测试结果。