简体   繁体   中英

Issue with Mockito when mocking an EntityManager

I am writing some unit test with Mockito and when I try to mock an EntityManager and run the unit test it is getting the following error:

java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/LockModeType at java.lang.ClassLoader.defineClass1(Native Method) ....

The stack tracepoinst tho the line where i have the following code:

private EntityManager entityManager = mock(EntityManager.class);

Any help is very much appreciated.

Flavio

May be the below link answer your problem.

crippled java ee

Don't mock types you don't own , especially an entity manager, instead write integration tests. You can use stuff like Arquilian, H2, etc, to help you write these these integration tests.

Further Readings

Sorry I don't really help you with this answer, but this is really a bad idea to mock types you don't own.

It's not clear from your question whether EntityManager is one of your own classes, or something in an external library.

If it's the former, I suggest you post the code for it here, so we can all see what the problem might be. Otherwise, we're just guessing.

If it's the latter, my next question is whether you are using a wrapper class. That is, you should consider writing a class called EntityManagerWrapper (or something similar) that has an EntityManager as a field, and exposes all the methods of that EntityManager that you wish to use. Each method of EntityManagerWrapper should be just one or two lines long, and do nothing other than calling the correct method of EntityManager . Then refactor all of your code that uses EntityManager , so that it uses EntityManagerWrapper instead.

There is no need to unit test EntityManagerWrapper , because it contains no logic of its own. However, you can easily mock EntityManagerWrapper when you unit test the other classes that use it. This should solve your problem.

Feel free to comment on this answer if it's not sufficiently clear what has to be done.

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