静态类的 Juint 测试



所以我正在尝试测试一个控制器,在我的代码中,它可以访问在启动时在main中创建的公共静态变量,称为settings。我已经尝试设置我的 Junit 测试@Before尽一切可能的方式创建在 main 中创建的相同静态类,但没有任何效果。

所以在我的代码中,我有

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();
}

然后我尝试测试一个使用静态游戏设置模型设置中的功能的控制器,但我无法让它工作。

这是我的朱尼特测试

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;

在测试期间为控制器提供静态类知识的正确内容是什么?希望这是有道理的

提前致谢

可以通过仅在测试用例中使用的构造函数传递静态变量,也可以使用 PowerMock 模拟变量。例如:

@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 应该是一个实例变量。

最新更新