Search code examples
javajunitclassloader

JUnit Class Path and ContextClassLoader inconsistency or my misunderstanding


What I am trying to do is to load .class file (compiled class file) from jar as a resource stream. This try is made from inside JUnit test case.

  1. test case compiles and runs without problem SO: AFAIK Asset class should be available in classpath
  2. full class name need to be consistent with its place in file structure SO: We can replace dots in package name with directory separator to get class file location
  3. We can access everything which is in current class path using getResourceAsStream method.

Let me present some code for better understanding.

package org.jboss.shrinkwrap.impl.nio.file;    
import org.jboss.shrinkwrap.api.asset.Asset;

public class FileStoreTestCase {
// (...)
@Test
public void usedSpace(){    
    final Class<?> classToAdd = Asset.class;
    final String pathToClass = new StringBuilder(classToAdd.getName().replace('.', File.separatorChar)).append(
            ".class").toString();

    final InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathToClass);

}

Problem is that in above code "in" variable is always null. Do you know why? And how I can get it to work?

Thanks for any input.


Solution

  • Try with replace('.', '/') i.e. use '/' instead of File.separatorChar