Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically detect class which is being mocked #282

Open
rohanlopes20 opened this issue Apr 13, 2024 · 2 comments
Open

Automatically detect class which is being mocked #282

rohanlopes20 opened this issue Apr 13, 2024 · 2 comments

Comments

@rohanlopes20
Copy link

Currently mock object is created as follows -

Mockery mockery = new Mockery();
DummyInterface dummyInterface = mockery.mock(DummyInterface .class);

This can be created like below as well. We don't have to explicitly provide class name.

Mockery mockery = new Mockery();
DummyInterface dummyInterface = mockery.mock();

This is in reference to pull request mockito/mockito#2779 (comment)

Below code can be added -

   private static <T> Class<T> getClassOf(T[] array) {
        return (Class<T>) array.getClass().getComponentType();
    }

    /**
     * Creates a mock object of type <var>typeToMock</var> and generates a name for it.
     * @param <T> is the class of the mock
     * @param  reified don't pass any values to it. It's a trick to detect the class/interface you want to mock.
     * @return the mock of typeToMock
     */
    public <T> T mock(T... reified) {
        if (reified.length > 0) {
            throw new IllegalArgumentException(
                    "Please don't pass any values here. Java will detect class automagically.");
        }
        return mock(getClassOf(reified));
    }
@olibye
Copy link
Member

olibye commented Apr 21, 2024

Nice, feel free to make a PR

@rohanlopes20
Copy link
Author

Not able to make PR/push changes to branch as not part of member group. Branch is already created on local.

Nice, feel free to make a PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants