rust - 如何在不将代码拆分成单独的函数的情况下为SPECS框架编写单元测试?

标签 rust specs

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

相关文章:

xcode - 在 Xcode 中使用 NSTask 在 AppKit 应用程序中运行时,Rust 1.4.0(或更高版本)cargo/rustc 崩溃

scala - Scala Specs BDD 库中的异常匹配器

scala - 如何将Specs2与Scalacheck结合使用以自动测试String参数?

scala - Scala 的 "specs"BDD 框架如何工作?

rust - Rust:为什么编译器将!! value转换为value?

debugging - Rust 的逐步交互式调试器?

c - 重新解释内存/指针

multithreading - 如何检查线程是否已在 Rust 中完成?

scala - 是否有规范匹配器可以取消装箱选项和任一