I have an abstract
class that I'd like to mock out for testing purposes:
public abstract class Foo {
public abstract void bar();
public void baz() {
System.out.print("Hi from baz!");
}
}
If I use easyMock Foo mock = createNiceMock(Foo.class)
and then call mock.baz()
I get a java.lang.NullPointerException
. If I change baz()
to final
, things work swimmingly (I assume this has to do with the fact EasyMock can't mock final
methods) but I would like to be able to call baz()
without doing this.
Is there a way to create a mock object using EasyMock that allows me to call my non- abstract
methods?
The one workaround I'm currently using is:
Foo mock = new Foo() {
@Override
public void bar() {
return;
}
}
but this is super ugly.
So I found a solution to my question. You can create partial mocks in EasyMock:
Foo mock = EasyMock.createMockBuilder(Foo.class)
.addMockedMethod("bar")
.createNiceMock();
The one caveat to this is that if the class has instance variables, as you are not using new
they won't be initialized! If anyone has a workaround for this aspect, that would be useful. That is creating a partial for this class:
public abstract class Foo {
public double myInstanceVariable = 2;
public abstract void bar();
public void baz() {
System.out.print("Hi from baz!");
}
}
Where it's possible to call mock.myInstanceVariable
and get 2
.
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.