#Unit testing with SystemState

12 messages · Page 1 of 1 (latest)

modest kindle
#

Why does this test not fail?


use bevy::ecs::system::SystemState;

fn test_commands(
    mut commands: Commands,
) {
    for _many_times in [0..20] {
        commands.spawn_empty();
    }
}

#[test]
fn modify_world_for_unit_test() {
    let mut world = World::default();
    let mut count_before_running_system_and_applying_commands = world.entities().len();

    let mut system_state: SystemState<Commands> = SystemState::new(&mut world);
    let mut commands = system_state.get_mut(&mut world);

    // Run the system, which puts commands into the SystemState's internal queue, supposedly
    test_commands(commands);
    world.increment_change_tick();

    // Apply the commands
    system_state.apply(&mut world);
    let mut count_after_apply = world.entities().len();

    assert_ne!(count_before_running_system_and_applying_commands, count_after_apply);
}
modest kindle
#

I'm trying to build up to being able to test my own systems that use system parameters like Commands, <On<Pointer<Click>>>, Queries, and Resources.

rancid sierra
#

Why do you want this test to fail? After spawning 20 entities I would expect the count of entities to be different

modest kindle
#

Exactly, it's NOT failing.

sturdy atlas
#

Can you change the assert to

assert_ne!(count_before_running_system_and_applying_commands, count_after_apply, "Expected the counts to be different but they were equal. {count_after_apply}");
modest kindle
#

That doesn't change anything because the two values are the same

#

I did try it.

#

Since the test succeeds, we don't get the string you added

rancid sierra
#

I guess to answer your question, the test doesn't fail because SystemState::apply applies all the commands, so the entities are spawned, and so there's a different entity count

#

Which matches your assert

modest kindle
#

sorry, I was away from the code and phrased it confusingly. The numbers for each of the two variables are thus: 0, 4. So the code that's supposed to add 20 entities doesn't add 20. The difference of 0 and 4 is only 4. Is it possible to not go through the entire command queue in each tick? This change results in the same 0, 4 result: ```rust test_commands(commands);
world.increment_change_tick();
system_state.apply(&mut world);
world.increment_change_tick();
world.increment_change_tick();
system_state.apply(&mut world);
world.increment_change_tick();
world.increment_change_tick();
system_state.apply(&mut world);
world.increment_change_tick();

// Apply the commands
system_state.apply(&mut world);
let mut count_after_apply = world.entities().len();```