Java 具有静态类的Juint测试
所以我尝试测试一个控制器,在我的代码中,它可以访问一个在启动时在main中创建的公共静态变量settings。我已经尝试过设置我的Junit tests@,然后尽一切可能创建在main中创建的相同静态类,但是什么都不起作用 所以在我的代码中Java 具有静态类的Juint测试,java,javafx,junit,Java,Javafx,Junit,所以我尝试测试一个控制器,在我的代码中,它可以访问一个在启动时在main中创建的公共静态变量settings。我已经尝试过设置我的Junit tests@,然后尽一切可能创建在main中创建的相同静态类,但是什么都不起作用 所以在我的代码中 public class Main extends Application { //static variables that can be referenced from anywhere in the application public static
public class Main extends Application {
//static variables that can be referenced from anywhere in the application
public static GameSettingsModel settings;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) throws IOException {
//initiate the GameSettingsModel
settings = new GameSettingsModel();
}
然后我试着测试一个控制器,它在静态游戏设置模式设置中使用一个函数,但是我不能让它工作
这是我的junit测试
public class Test extends TestSuite {
private IGame game;
private IBall ball;
private IPaddle paddle;
private IBrick player1Wall;
private IPlayer player1;
private IPlayer player2;
public static GameSettingsModel settings;
@Before
public void setUp() {
//initiate the GameSettingsModel
settings = new GameSettingsModel();
player1Wall = new BrickModel(0,0,20);
player1 = new PlayerModel();
player2 = new PlayerModel();
ball = new BallModel();
paddle = new PaddleModel();
game = new SinglePlayerController();
}
因此,现在当我尝试运行测试时,我在代码尝试调用settings.reset()的行上得到一个NullPointerException
在测试期间,给我的控制器关于静态类的正确知识是什么?希望这是有道理的
提前感谢您可以通过仅在测试用例中使用的构造函数传递静态变量,也可以使用模拟变量。例如:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyStaticClass.class })
public class MyTest {
@Before
public void setup() {
// Here you mock the variable with the method that is going to be executed
PowerMockito.mockStatic(MyStaticClass.class);
PowerMockito.when(MyStaticClass.staticMethod).thenReturn(result);
}
}
希望这就是您想要的。您可以通过仅在测试用例中使用的构造函数传递静态变量,也可以使用模拟变量。例如:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyStaticClass.class })
public class MyTest {
@Before
public void setup() {
// Here you mock the variable with the method that is going to be executed
PowerMockito.mockStatic(MyStaticClass.class);
PowerMockito.when(MyStaticClass.staticMethod).thenReturn(result);
}
}
希望这就是您想要的。不要从实例方法设置静态变量。事实上,我们没有可变的静态变量。根据您提供的代码,
设置
应该是实例变量。不要从实例方法设置静态变量。事实上,我们没有可变的静态变量。根据您提供的代码,settings
应该是一个实例变量。实际上不是。我们需要一个包含抛出的代码和异常堆栈跟踪的实数。我们需要一个真正的程序,包括抛出的代码,以及异常堆栈跟踪。我只是添加了很多构造函数,因为我知道我应该在某个点删除静态变量,这一切都可以正常工作。我只是添加了很多构造函数,因为我知道我应该在某个点删除静态变量,这一切都可以正常工作,甚至只是传递给应用程序的控制器,甚至只是传递给应用程序控制器的局部变量。