我正在尝试为使用SPECS框架的Rust程序编写测试。我不确定如何在系统的run
函数上运行单元测试,因为它使用框架的存储类型来读取值。有谁有解决这个问题的好方法?这是我的运动系统代码:
use specs::prelude::*;
use crate::components::{Position, Velocity, Antenna};
pub struct Movement;
impl<'a> System<'a> for Movement {
type SystemData = (
WriteStorage<'a, Position>,
WriteStorage<'a, Velocity>,
);
fn run(&mut self, (mut position, velocity): Self::SystemData) {
for(pos, vel) in (&mut position, &velocity).join() {
pos.x += vel.x;
pos.y += vel.y;
}
}
}
最佳答案
您可以通过转发到run
中的函数来简化Movement
,然后测试该函数。使此新功能在P和V上具有通用的位置和速度。
您可能需要为P和V添加一些特征,并为WriteStorage
以及将用于测试的任何类型实现它们(也许只是&[f32])
就像是:
use specs::prelude::*;
use crate::components::{Position, Velocity, Antenna};
pub struct Movement;
trait ValueList<T> { /* ... */ }
impl<T> ValueList<T> for WriteStorage<'a, T> { /* ... */ }
impl<T> ValueList<T> for &[T] { /* ... */ }
impl Movement {
fn run_impl<P,V>(position:P, velocity:V)
where
P: ValueList<Position>
V: ValueList<Velocity>
{
for(pos, vel) in (&mut position, &velocity).join() {
pos.x += vel.x;
pos.y += vel.y;
}
}
}
impl<'a> System<'a> for Movement {
type SystemData = (
WriteStorage<'a, Position>,
WriteStorage<'a, Velocity>,
);
fn run(&mut self, (mut position, velocity): Self::SystemData) {
Self::run_impl(position, velocity);
}
}
#[test]
fn test_run() {
let p:Vec<Position> = vec![...];
let v:Vec<Velocity> = vec![...];
Movement::run_impl(p,v);
...
}
关于rust - 如何在不将代码拆分成单独的函数的情况下为SPECS框架编写单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65722021/