Wie kann man Wandkollisionslogik in einer Java-"-Motor-Klasse" -Klasse ohne Test-Konstrukteure nur für Tests hinzufügen?Java

Java-Forum
Anonymous
 Wie kann man Wandkollisionslogik in einer Java-"-Motor-Klasse" -Klasse ohne Test-Konstrukteure nur für Tests hinzufügen?

Post by Anonymous »

Ich habe eine Klasse Physicsgine , die die Spiellogik zusammenfasst. Intern wird eine Ball Instanz in einem privaten Feld enthält und bei jedem Update überprüft es auf Wandkollisionen und ruft entweder BounceHorizontal () oder bouncevertical () auf dem Ball auf. Mein Produktionscode sieht ungefähr so ​​aus: < /p>

Code: Select all

public class PhysicsEngine {
private Ball ball = new Ball( /* ... initial args ... */ );
private int paddleDirection = 0;
// other fields...

public void setPaddleDirection(int dir) {
this.paddleDirection = dir;
}

public void update() {
// 1) Move paddle, ball, etc.
ball.updatePosition();
checkWallCollision();
// 2) Check other collisions that might happend...
}

private void checkWallCollision() {
double x = ball.getPosition().getX();
// suppose WALL_LEFT and WALL_RIGHT are constants
if (x - BALL_RADIUS = WALL_RIGHT) {
ball.bounceHorizontal();
}
double y = ball.getPosition().getY();
if (y - BALL_RADIUS 
Ich möchte einen Unit-Test für nur die Wandkollisionslogik schreiben, z. B.:
@Test
void testBallBouncesOffRightWall() {
PhysicsEngine engine = new PhysicsEngine();

// somehow position the internal ball so it is just past the right wall
// engine.ball.position = new Point2D(WALL_RIGHT - BALL_RADIUS + 1, 100);

engine.update();

// verify that bounceHorizontal() was called exactly once on the ball
// verify(...);
}
< /code>
Das Problem ist: < /p>

PhysicsEngine
enthüllt nicht den Ball über Konstruktor oder Setter
(es ist ein privates Feld). /> Was ist der akzeptierte Weg zu: < /p>

Ersetzen oder verspotten diesen privaten Ball < /code> Instanz in Physicsgine < /code> In
Mein Junit -Test? bounceHorizontal () oder bouncevertical () wurde genannt? Ich möchte lieber keine privaten Felder freilegen oder Konstruktoren nur zum Testen hinzufügen - welche Technik (en). Kann ich das private Feld zum Testzeit eingeben oder manipulieren?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post