简体   繁体   中英

Can we Mock any object or class but not in Junit

Which mock framework can we use to mock a class or its object. We usually use mocking framework while implementing junit test cases, but how can i mock a class/its's object not in any test case class but a normal class.

Is it possible to do so?

While mock-frameworks are normally done only in test code, that's not a requirement. You could certainly import your favorite mocking framework as a compile (not test) dependency, and then in any src/main/java class, you would be able to constuct mocks in the normal manner (eg @Mock etc).

Why you would do that, I don't know. And therein lies a much more intersting question. Realize mock-frameworks operate via reflection and sometimes by byte-code manipulation. That poses some concern for production-quality code, but now you have it in mainline source. Depending on what you are REALLY trying to accomplish, there might be better ways - eg de-encapsulation, AoP, stubs, etc.

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