java - 在每个单元测试开始时重新加载静态变量

标签 java android junit classloader robolectric

我正在使用大量静态方法对 SDK 进行单元测试。而且我不希望我在 test1() 中执行的操作影响我在 test2() 中执行的操作。在每次测试开始时,我需要将 SDK 中的所有静态变量恢复到未初始化状态,就好像它们没有被加载一样。然后再次加载它们。关于如何做到这一点的任何建议? Robolectric 中是否有类似的规定?因为我用它来进行单元测试。在 plan English 中,我基本上想要的是在每次测试开始时重新开始。

@Test
public void test1() throws Exception {
    // Setup all the device info values
    MyDeviceInfoClass.setDeviceModel().equals("Nexus 4");
    MyDeviceInfoClass.setDeviceOperatingSystem().equals("Android_3.4b5");

    // Verify all the device info values set previously
    assertTrue(MyDeviceInfoClass.getDeviceModel().equals("Nexus 4"));
    assertTrue(MyDeviceInfoClass.getDeviceOperatingSystem().equals("Android_3.4b5"));
}

这是第一个测试,它成功了。就应该这样。然后在第二个测试中:

@Test
public void test2() throws Exception {
      // Setup all the device info values
      MyDeviceInfoClass.setDeviceOperatingSystem().equals("Android_4.2");

      //The following line also succeeds if test1() is finished. But I do not want that. This line should throw an assertion error because we did not specify what the device is over here in test2().
      assertTrue(MyDeviceInfoClass.getDeviceModel().equals("Nexus 4"));
      //This will succeed just the way it should be.
      assertTrue(MyDeviceInfoClass.getDeviceOperatingSystem().equals("Android_4.2"));
}

我不希望第一个测试中设置的值影响第二个测试中获取的值。上面显示的测试是简单的例子。但我正在单元测试的 SDK 比这更复杂。

更清楚地说,我不希望 test1() 中设置的值对 test2() 中完成的操作有任何影响。如果我在 test1() 中将设备模型设置为 Nexus 4,就像这样 MyDeviceInfoClass.setDeviceModel().equals("Nexus 4"),当我通过 MyDeviceInfoClass.setDeviceModel 获取它时,第二个测试 test2() 不必知道它().equals("Nexus 4").我希望在我的单元测试之间完全隔离。

放弃静态方法也不是一种选择。请告诉我如何实现这一目标。

编辑: 由于项目中涉及的某些复杂性,在测试开始之前重置所有静态变量也不是一种选择。

最佳答案

唯一一次卸载静态变量是在加载相关类的类加载器被垃圾回收时。

解决您的问题的一种方法是使用您自己的类加载器。有一个很棒的 SO 问题 here涵盖了相当广泛的细节。

另一种选择是在每次测试之前简单地重置值。您可以在测试类中提供一个带注释的 @Before 方法来重置它们,必要时使用反射。

关于java - 在每个单元测试开始时重新加载静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17496850/

相关文章:

javax.persistence.EntityNotFoundException'异常。无法评估 models.Anagrafica_$$_jvst834_0.toString()

java - LibGDX box2d 检测对象的特定实例

java - 在 Liferay 中获取网页内容的最新工作流程状态

android - 表示室内地图的数据结构

java - SureFire 插件 : -"The forked VM terminated without saying properly goodbye. VM crash or System.exit called ? " 的问题

mysql - 使用 `.createSQLQuery` 截断后 spring/hibernate 不会回滚事务

java - 如何获得整个 servlet 的连接?

android - 在 Android 上的 libgdx 中,如果应用程序被杀死,我该如何保存游戏状态?

android - Appsync 离线查询在 android 中不起作用

java - JUnit 断言ArrayEquals