Цитата:
Помогите написать JUnit-тесты для данной программы в соответствии с логикой программы.
Код:
package laba2;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
class square extends JComponent {
private static final Random random = new Random();
private Color color;
private double x, y;
private double dx, dy;
public square() {
setSize(50, 50);
dx = 1;
dy = 1;
color = Color.black;
}
@Override
public void paintComponent(Graphics g) {
setBounds((int)x, (int)y, getWidth(), getHeight());
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
public void setColor(Color color) {
this.color = color;
}
public double getsquareX() {
return x;
}
public double getsquareY() {
return y;
}
public void invertDx() {
int sign = Integer.signum((int)-dx);
dx = sign * (2 + random.nextInt(3));
}
public void invertDy() {
int sign = Integer.signum((int)-dy);
dy = sign * (2 + random.nextInt(3));
}
public void advance() {
x += dx;
y += dy;
}
@Override
public String toString() {
return "square{" +
"x=" + x +
", y=" + y +
", dx=" + dx +
", dy=" + dy +
'}';
}
}
class squareMover implements ActionListener {
private square square;
private Container pane;
public squareMover(square square, Container pane) {
this.square = square;
this.pane = pane;
}
private boolean squareHitsUpperBorder() {
return square.getsquareY() <= 0;
}
private boolean squareHitsLowerBorder() {
return square.getsquareY() >= pane.getHeight() - square.getHeight();
}
private boolean squareHitsLeftBorder() {
return square.getsquareX() <= 0;
}
private boolean squareHitsRightBorder() {
return square.getsquareX() >= pane.getWidth() - square.getWidth();
}
@Override
public void actionPerformed(ActionEvent e) {
square.advance();
if (squareHitsUpperBorder() || squareHitsLowerBorder()) {
square.invertDy();
square.setColor(squareHitsUpperBorder() ? Color.RED : Color.BLUE);
}
if (squareHitsLeftBorder() || squareHitsRightBorder()) {
square.invertDx();
square.setColor(squareHitsLeftBorder() ? Color.YELLOW : Color.WHITE);
}
pane.repaint();
}
}
class Window extends JFrame {
private final square square = new square();
public Window() {
setTitle("Лабораторна робота № 2");
setSize(400, 400);
setResizable(false);
setLayout(null);
getContentPane().setBackground(Color.GREEN);
getContentPane().add(square);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
new Timer(5, new squareMover(square, getContentPane())).start();
}
}
public class Launcher {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Window window = new Window();
window.setVisible(true);
}
});
}
}