我使用大量静态方法对SDK进行单元测试。我不希望我在test1()中执行的操作对我在test2()中执行的操作产生影响。在每次测试开始时,我需要SDK中的所有静态变量回到未初始化状态,就好像它们没有加载一样。然后再加载它们。有关如何做到这一点的任何建议?在Robolectric中有这样的条款吗?因为我用它来进行单元测试。在计划英语中,我基本上想要的是在每次测试开始时的干净的石板。在每个单元测试开始时重新加载静态变量
@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()中将设备模型设置为test1(),就像这个MyDeviceInfoClass.setDeviceModel()。equals(“Nexus 4”),当我通过MyDeviceInfoClass.setDeviceModel获取它时,第二个测试test2()不必知道它().equals(“Nexus 4”)。我想在我的单元测试之间完全隔离。
远离静态方法不是一种选择。请告诉我如何才能做到这一点。
编辑: 测试开始前清除所有的静态变量是不是因为某些参与该项目的复杂性,任何一个选项。
你有没有考虑过把每个测试放在一个单独的程序中?这将隔离它们,并确保每个测试都以新鲜初始化的类开始。 –
你是指在不同的文件?在这种情况下,不可能为每个单元创建一个不同的项目。 – iamronak
是的,每个文件一个测试。 –