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 to mock #2779

Merged
merged 6 commits into from Nov 14, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/main/java/org/mockito/Mockito.java
Expand Up @@ -1901,6 +1901,23 @@ public class Mockito extends ArgumentMatchers {
*/
public static final Answer<Object> RETURNS_SELF = Answers.RETURNS_SELF;

/**
* Creates mock object of requested class or interface.
* <p>
* See examples in javadoc for {@link Mockito} class
*
* @param reified don't pass any values to it. It's a trick to detect the class/interface you want to mock.
* @return mock object
szpak marked this conversation as resolved.
Show resolved Hide resolved
*/
public static <T> T mock(T... reified) {
if (reified.length > 0) {
throw new IllegalArgumentException(
"Please don't pass any values here. Java will detect class automagically.");
szpak marked this conversation as resolved.
Show resolved Hide resolved
}
Class<T> classToMock = (Class<T>) reified.getClass().getComponentType();
return mock(classToMock, withSettings());
}

/**
* Creates mock object of given class or interface.
* <p>
Expand Down
8 changes: 8 additions & 0 deletions src/test/java/org/mockito/MockitoTest.java
Expand Up @@ -133,4 +133,12 @@ public void shouldStartingMockSettingsContainDefaultBehavior() {
// when / then
assertThat(settings.getDefaultAnswer()).isEqualTo(Mockito.RETURNS_DEFAULTS);
}

@Test
@SuppressWarnings({"DoNotMock", "DoNotMockAutoValue"})
public void automaticallyDetectsClassToMock() {
List<String> mock = Mockito.mock();
Mockito.when(mock.size()).thenReturn(42);
assertThat(mock.size()).isEqualTo(42);
}
}
Expand Up @@ -339,4 +339,14 @@ class InlineClassTest {

verify(mock).returnsResult()
}

@Test
@SuppressWarnings("DoNotMock", "DoNotMockAutoValue")
fun automaticallyDetectsClassToMock() {
val mock: WithResult = mock()

`when`(mock.returnsResult()).thenReturn(Result.success("OK"))

assertEquals("OK", mock.returnsResult().getOrNull())
}
}