In Java, can I instantiate an anonymous subclass from a class object?

I have a factory method that creates objects that will be used in unit tests. All these objects are made from one base class:

public static <T extends BaseEntity> T modMake(Class<T> clazz)
{
    try {
        return clazz.newInstance();
    } catch (InstantiationException e) {
        // Should never happen
        throw new AssertionError(e);
    } catch (IllegalAccessException e) {
        // Should never happen
        throw new AssertionError(e);
    }
}

Now I want to override the getter method from this base class, but only for tests. I usually do this with an anonymous class, for example ( Nodeis one of the subtypes BaseEntity):

public static Node nodMake()
{
    return new Node() {
        @Override
        public long ixGet() { return 1; }
    };
}

Can I do this in a function with an argument Classtoo?

+2
source share
2 answers

Lose your factory method and use a mocking API like EasyMock to achieve the behavior you describe.

Then your code will look something like this:

long returnValue = 12;

Node nodeMock = createMock(Node.class);
expect(nodeMock.ixGet()).andReturn(returnValue);
replay(nodeMock);

//add test code here

verify(nodeMock);

, :

, .

( ), , , Java.

-, @Jonathan , API.

EasyMock .

+3

, . , , -, . Javassist BCEL - .

0

Source: https://habr.com/ru/post/1793413/


All Articles