0

我正在为我的程序开发我的 Ant 构建器,特别是处理文件的路径。

我达到了一个非常简单的解决方案,在我的常量界面中添加了两个字段:

/** The actual jar file where the class is run */
public static final File JAR_FILE = new File(MagicHogwarts.class.getProtectionDomain().getCodeSource().getLocation().getPath());

/** The path to the main folder where the file .jar is run */
public static final String BASE_DIRECTORY = JAR_FILE.getAbsolutePath().replace(JAR_FILE.getName(), "");

在处理文件的每种方法中,我只需询问相对于 jar 所在的主文件夹的路径,然后首先添加 BASE_DIRECTORY,这至少在运行 jar 的 eclipse 中的 macOSX 中都可以正常工作。

对这个快速解决方案感到满意,我运行了我的测试。那失败了。问题似乎出在 Constants 接口上,无法创建JAR_FILE,因为getLocation返回 null,然后getPath失败。

但我不明白为什么。

所以我尝试模拟接口,由于 var 被声明为 static final ,因此存在明显问题,所以我尝试使用 PowerMock:

@RunWith(PowerMockRunner.class)
@PrepareForTest({GameWindow.class,Constants.class})
public class MapReaderTest {

@Test
public void testReadingExampleMap() throws Exception {
    mockStatic(GameWindow.class);
            mockStatic(Constants.class);
    TextureLoader tl = createMock(TextureLoader.class);
    Texture tx = createMock(Texture.class);
    expect(GameWindow.getTextureLoader()).andReturn(tl);
            expect(Constants.BASE_DIRECTORY).andReturn("/Users/Gianmarco/Documents/java/MagicHogwarts/").anyTimes();
    expect(tl.getTexture("/Users/Gianmarco/Documents/java/MagicHogwarts/bin/mh/test/sewer_tileset.png")).andReturn(tx);
    expect(tx.getImageHeight()).andReturn(32).anyTimes();
    expect(tx.getImageWidth()).andReturn(32).anyTimes();
    replay(GameWindow.class);
            replay(Constants.class);
    replay(tl);
    replay(tx);

    // Act
    Map map = new TMXMapReader().readMap("/bin/mh/test/sewers.tmx");//mapFile.getAbsolutePath());

    // Assert
    assertEquals(Map.ORIENTATION_ORTHOGONAL, map.getOrientation());
    assertEquals(50, map.getHeight());
    assertEquals(50, map.getHeight());
    assertEquals(24, map.getTileWidth());
    assertEquals(24, map.getTileHeight());
    assertEquals(2, map.getLayerCount());
}
}

但是我得到了一个 ExceptionInInitializerError,第 60 行 Constants,即声明 JAR_FILE 的行,该错误是由 NullPointerException 引起的。

我认为下一步是将接口转换为类,也许 powermock 无法以这种方式处理接口。

运行,得到一个 NoClassDefFoundError。仍然没有结果,我不知道该怎么办。所以我尝试了反思。

我使用了这个静态方法:

static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);

    // remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, newValue);
}

调用它:

setFinalStatic(Constants.class.getField("JAR_FILE"), null);
setFinalStatic(Constants.class.getField("BASE_DIRECTORY"), "my/path/hardcoded");

但这都不起作用,我得到了一个 ExceptionInInitializerError ,其中包含一个包含sun.mic.Unsafe.ensureClassInitialized(Native Method)sun.reflect 等的堆栈。

我花了几个小时来解决这个问题,我得出的结论是问题出在 JAR_FILE 以及用于初始化它的方法上,因为即使final从常量中删除修饰符我也无法更改值调用Constants.JAR_FILE = null

我为解决问题所做的事情是:

/** The actual jar file where the class is run */
    public static final File    JAR_FILE            = (MagicHogwarts.class.getProtectionDomain().getCodeSource().getLocation() == null ? null : new File(MagicHogwarts.class.getProtectionDomain().getCodeSource().getLocation().getPath()));

    /** The path to the main folder where the file .jar is run */
    public static final String  BASE_DIRECTORY      = (JAR_FILE != null ? JAR_FILE.getAbsolutePath().replace(JAR_FILE.getName(), "") : "/Users/Gianmarco/Documents/java/MagicHogwarts/");

这是使用 if 语句的粗鲁、非常不愉快和可怕的方式。

我的问题是,是否有任何不同的方法来获取 jar 的基本目录和/或从终端行调用的文件,#java Myclass可以在正常处理(也是 jar)和测试中使用

我达到的解决方案是有效的,但我认为将一些测试代码硬编码到一个类中并不是一件好事,实际上使用 if 就像告诉常量类“如果我正在测试,给我这个模拟字符串,否则给我真正的道路”。如果在正常程序行为中没有用,我希望将我的测试代码与我的类分开(应该如此)。

4

1 回答 1

0

测试时不应该依赖绝对路径,因为它会使测试变得脆弱且不可移植。

与其寻找绝对路径,不如寻找资源。最好使用 Class.getResource 或 Class.getResourceAsStream 来读取。

对于前者,您可以检索 URL。如有必要,可以使用 url.toExternalForm 将其转回绝对路径,但是一旦您拥有所需的资源,这应该就足够了。

于 2013-10-20T09:33:12.227 回答