简体   繁体   中英

How to mock final class in java by using EasyMock?- Junit test

I have final class and with constructor for that...

I have problem to mock this class. I came to know that i cannot use EasyMock for final class. But in my project i should use easymock only. Is there a way to mock this class? Can you please anyone help me in this?

//A a = createMock(A.class);//IllegalException occuring while running this test case


For example :

final class A {

private int a;
  A(int a){
this.a = a;
}

}

It's impossible to mock a final class with pure EasyMock. You'll have to add in something like PowerMock , which integrates well with EasyMock. Or you write a test that doesn't require mocking of a final class.

The best I can think of is that if your final class implements any interface (considering that the interface includes the methods you need to use in your test), you can always create instances of another class that implements that same interface and use this as the mock or use dynamic proxies .

The problem is that sometimes finding workarounds to requirements will exponentially multiply the work required to do something when you already know that tools like PowerMock are out there.

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