문제

.java 파일을 작성 해야하는 코드를 테스트하고 해당 .class 파일을 작성해야합니다.

".class"파일이 생성되었는지 확인하기 위해 테스트를 작성하려면 어떻게해야합니까? 이미 존재에 대한 테스트를 추가했는데 이제 파일을 테스트하려고합니다. 유효한 클래스 파일입니다.

나는 시도했다

 try  {
      Class.forName("Hello");
      throw AssertError();
 } catch( ClassNotFoundException e ) {
 }

 program.createClass();
 Class.forName("Hello");

그러나 파일이 클래스 경로에 생성되는 경로를 동적으로 추가하는 방법을 실제로 모르겠습니다.

편집하다

로드 된 URL 클래스는 작업을 수행합니다.

이것이 내 시험의 모습입니다.

@Test
void testHello() throws MalformedURLException, ClassNotFoundException {
    URL[] url = {
            new URL("file:/home/oreyes/testwork/")
    };

    try {
        new URLClassLoader(url).loadClass("Hello");
        throw new AssertionError("Should've thrown ClassNotFoundException");
    } catch ( ClassNotFoundException cnfe ){

    }
    c.process();
    new URLClassLoader(url).loadClass("Hello");
}
도움이 되었습니까?

해결책

새 인스턴스를 사용하십시오 URLClassLoader, 대상 클래스 파일을 생성 한 루트 폴더를 가리키고 있습니다. 그런 다음 사용하십시오 Class.forName(String,ClassLoader); 동적으로 생성 된 방법 URLClassLoader 새 클래스를로드합니다.

작동 함을 보여주기 위해 다음 테스트 케이스는 소스 파일을 생성하고 Java 코드를 작성하여 Java 6 ToolProvider 인터페이스를 사용하여 컴파일합니다. 그런 다음 UrlClassLoader를 사용하여 클래스를 동적으로로드하고 클래스 이름으로 반사 호출을 호출하여 실제로 생성 된이 클래스인지 확인합니다.

@Test
public void testUrlClassLoader() throws Exception {
    Random random = new Random();
    String newClassName = "Foo" + random.nextInt(1000);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    List<File> files = new ArrayList<File>();
    File sourceFolder = new File(".");
    File sourceFile = new File(sourceFolder, newClassName + ".java");
    FileWriter fileWriter = new FileWriter(sourceFile);
    fileWriter.write("public class " + newClassName + " { { System.out.println(\""
            + newClassName + " loaded\"); }}");
    fileWriter.close();
    files.add(sourceFile);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
            .getJavaFileObjectsFromFiles(files);
    compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    fileManager.close();

    URL url = sourceFolder.toURI().toURL();
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url });
    Object newInstance = urlClassLoader.loadClass(newClassName).newInstance();
    assertEquals(newClassName, newInstance.getClass().getName());
}

다른 팁

클래스를 검증하기 위해 클래스를로드하는 대신 "file hello.class"와 같은 명령으로 껍질을 벗기기 위해 Java 클래스 파일인지 확인하거나 심지어 클래스를로드하기 위해 Java의 하위 프로세스를 생성하는지 확인할 수 있습니다. 테스트 외부 JVM.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top