Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you cast RuntimeEnvironment.application?

When running Robolectric tests, RuntimeEnvironment.application's type is determined by your configuration. Say I configured RoboApplication.class as my test application, I can cast RuntimeEnvironment.application to my type without fail.

RoboApplication app = (RoboApplication) RuntimeEnvironment.application;
app.doSomething();

However, once I integrate PowerMock, the cast line fails with

java.lang.ClassCastException: RoboApplication cannot be cast to RoboApplication

How can I workaround this issue?

like image 355
Some Noob Student Avatar asked Sep 05 '26 11:09

Some Noob Student


1 Answers

This is a problem because PowerMock and Robolectric are mutually incompatible due to the use of their own classloaders.

Even though the names are the same, the Class objects aren't actually the same: Robolectric and PowerMock both work by loading the test through custom classloaders. These classloaders change the classes in question, allowing you to replace static/final Android system classes and methods [Robolectric] or all static/final classes [PowerMock]. This is part of the reason that PowerMock and Robolectric both rely on having their own JUnit4 Runner: That way they can load the appropriate classes from their own modifying classloaders.

Because of this, the instances can't be cast to one anothers' classes, even though they have the same name and originate from the same source file: Each framework can change the class implementation, so they aren't necessarily compatible with one another.

You'll need to choose one framework or the other: Use Robolectric shadows, possibly with EasyMock or Mockito directly, or use PowerMock to stub the Android infrastructure calls yourself manually.

See also:

  • ClassCastException when casting to the same class
  • cast across classloader?
like image 99
Jeff Bowman Avatar answered Sep 08 '26 03:09

Jeff Bowman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!