Skip to content

Instantly share code, notes, and snippets.

@tonvanbart
Last active July 12, 2024 01:21
Show Gist options
  • Save tonvanbart/debb9c2fbcb99a8d7a0ef5a46a6ff385 to your computer and use it in GitHub Desktop.
Save tonvanbart/debb9c2fbcb99a8d7a0ef5a46a6ff385 to your computer and use it in GitHub Desktop.
How to capture constructor arguments while Mockito is mocking the constructed class. Not pleasant but it works.
class Dog {
String name;
public Dog(String name) {
this.name = name;
}
public String bark() {
return name + " says: Woof!";
}
}
/**
* Constructing a new House adds a dog named "Fido".
*/
public class House {
public Dog dog;
public House() {
this.dog = new Dog("Fido");
}
public String ringBell() {
return dog.bark();
}
}
public class HouseTest {
@Test
void tryCaptureMockedConstruct() {
try (
MockedConstruction<Dog> mocked = mockConstruction(Dog.class, (mock, context) -> {
String passedDogname = (String) context.arguments().get(0);
assertEquals("Fido", passedDogname);
when(mock.bark()).thenReturn("Kef kef kef!");
})
) {
House house = new House();
assertThat(house.ringBell(), is("Kef kef kef!"));
}
}
@Test
void tryVerify() {
MockedConstruction<Dog> mocked = mockConstruction(Dog.class, (mockedDog, context) -> {
when(mockedDog.bark()).thenReturn("Yipyipyip!");
});
House house = new House();
assertThat(house.ringBell(), is("Yipyipyip!"));
Dog dog = mocked.constructed().get(0);
verify(dog, times(2)).bark();
mocked.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment