简体   繁体   中英

EasyMock java: incompatible types: java.lang.ClassLoader cannot be converted to java.lang.Class<capture#1 of ? extends >

I am writing Testcases using Easymock for following code:

public class MyClass{
 public String getToken(String scope){
        String requestToken = "";
        try {
            URL keyStoreFile = getClass().getClassLoader().getResource(keyStoreFileName);
            /*rest of the code*/
            }
}

I need to mock above line. It isrefering property file. I have mocked as:

@RunWith(PowerMockRunner.class)
public class MyClassTestCase {
@Test
public void testToken(){
MyClass myclass= new Myclass();

 PowerMock.createPartialMock(MyClass.class, "getClass");
        expect(myclass.getClass()).andReturn(classLoader);
        expect(classLoader.getResource(null)).andReturn(null);
        replay(classLoader,myclass);
}
}

Tried many ways, but not able to get through this. Please help.

Thank you in advance.

Sadly, your code doesn't compile at all and a lot of pieces are missing. Also, you are not giving the line where the compilation error occurs.

Finally, mocking that low is useless. I would just test with a keystoreFileName dedicated to test. And that's it.

Anyhow, I will guess. This line expect(myclass.getClass()).andReturn(classLoader); will give an error similar to your error. Because getClass() is returning a Class<?> (which is a java.lang.Class<capture#1 of ? extends> in the compiler way to speak). But you are passing a classloader to andReturn . Which is not and will never be a Class<?> .

But I think you want to do the following:

@Test
@SuppressWarnings("unchecked")
public void testToken(){
  Class<MyClass> clazz = PowerMock.createMock(Class.class);
  ClassLoader classLoader = PowerMock.createMock(ClassLoader.class);

  MyClass myclass = PowerMock.createPartialMock(MyClass.class, "getClass");
  EasyMock.expect((Class<MyClass>) myclass.getClass()).andReturn(clazz);
  expect(classLoader.getResource(null)).andReturn(null);

  replay(clazz, classLoader, myclass);

  myclass.getToken("scope");
}

So you basically just need to cast. And add a @SuppressWarnings("unchecked") . There are no cleaner way.

Then, it won't work anyway because the JVM won't let you mock a Class . Which will bring you back to my advice: Don't mock this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM