![](/img/trans.png)
[英]How can I read from a component and write to a new entity with that same component in Rust SPECS?
[英]How can I write a unit test for the SPECS framework without splitting my code into separate functions?
我正在嘗試為使用 SPECS 框架的 Rust 程序編寫測試。 我不確定如何在系統run
function 上運行單元測試,因為它使用框架的存儲類型來讀取值。 有沒有人有解決這個問題的好方法? 這是我的運動系統代碼:
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;
}
}
}
您可以通過轉發到Movement
中的 function 來簡化run
,然后改為測試該 function。 使這個新的 function 在 P 和 V 上通用,用於 position 和速度。
您可能需要為 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);
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.