Skip to content
learnFRC.org
programmingreference

Physics Simulation & Unit Testing

Writing automated JUnit tests for commands and simulating physical mechanisms on your laptop.

Testing code directly on physical hardware consumes battery charge and risks mechanism damage during early development. Combining JUnit tests with WPILib physics simulation verifies command logic before deploying to the robot.

WPILib commands follow a deterministic lifecycle (initialize, execute, isFinished, end), making them straightforward to unit-test with JUnit 5:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class IntakeCommandTest {
@Test
public void testIntakeFinishesOnSensorTrigger() {
MockIntakeSubsystem intake = new MockIntakeSubsystem();
RunIntakeCommand command = new RunIntakeCommand(intake);
command.initialize();
assertFalse(command.isFinished());
// Simulate sensor detecting game piece
intake.setSensorTriggered(true);
command.execute();
assertTrue(command.isFinished(), "Intake command must finish when game piece is detected");
}
}

WPILib includes physics models for standard mechanisms:

  • ElevatorSim: Simulates motor voltage, gravity, carriage mass, and drum radius.
  • SingleJointedArmSim: Simulates arm length, mass, moment of inertia, and angle-dependent gravity torque.
  • FlywheelSim: Simulates moment of inertia and friction drag.

WPILib includes motor curves via DCMotor, capturing stall torque, free speed, and stall current for all standard FRC motors:

  • Modern brushless motors: DCMotor.getKrakenX60(numMotors), DCMotor.getNEO(numMotors), DCMotor.getFalcon500(numMotors).
  • Compact high-performance motors: DCMotor.getX44(numMotors) and DCMotor.getMinion(numMotors).
  • Brushed motors: DCMotor.getCIM(numMotors) and DCMotor.get775Pro(numMotors).

Update your physics model inside simulationPeriodic():

@Override
public void simulationPeriodic() {
// 1. Pass applied motor voltage into the physics simulator
m_armSim.setInputVoltage(m_motor.getSimState().getMotorVoltage());
// 2. Advance the physics world by 20ms
m_armSim.update(0.020);
// 3. Update simulated sensor positions to close the loop
double motorRotations = (m_armSim.getAngleRads() / (2.0 * Math.PI)) * GEAR_RATIO;
m_motor.getSimState().setRawRotorPosition(motorRotations);
}

In VS Code:

  1. Press F5 or run WPILib: Simulate Robot Code on Desktop.
  2. Select SimGUI.
  3. Open the Mechanism2d window to view 2D vector animations of your arm and elevator tracking setpoints.
Tuning in Simulation

You can tune initial PID and feedforward gains in simulation using WPILib’s ProfiledPIDController before hardware is built. The calculated gains will often be within 15% of the real hardware values.

Verified Sources & Standards

Evergreen Standard Verified: Sep 25, 2026