1

我正在尝试为使用 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;
        }
    }
}
4

1 回答 1

0

您可以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);
   ...
}
于 2021-01-15T06:56:10.917 回答