[英]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: 我正在使用Easymock为以下代码编写测试用例:
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. 我只是用专用于测试的keystoreFileName
进行测试。 And that's it. 就是这样。
Anyhow, I will guess. 无论如何,我会猜到。 This line expect(myclass.getClass()).andReturn(classLoader);
这行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). 因为getClass()
返回Class<?>
(以编译器的方式讲,它是java.lang.Class<capture#1 of ? extends>
)。 But you are passing a classloader
to andReturn
. 但是您andReturn
classloader
传递给andReturn
。 Which is not and will never be a Class<?>
. 哪个不是,永远也不会是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")
. 并添加一个@SuppressWarnings("unchecked")
。 There are no cleaner way. 没有更清洁的方法。
Then, it won't work anyway because the JVM won't let you mock a Class
. 然后,它无论如何都无法工作,因为JVM不允许您模拟Class
。 Which will bring you back to my advice: Don't mock this. 这将带您回到我的建议:不要嘲笑这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.