Skip to content

Instantly share code, notes, and snippets.

@sachi-d
Created November 3, 2020 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sachi-d/05422b1afe47761106e07d8f0c40b7a3 to your computer and use it in GitHub Desktop.
Save sachi-d/05422b1afe47761106e07d8f0c40b7a3 to your computer and use it in GitHub Desktop.
import junit.framework.TestCase;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class DogTest extends TestCase {
@Test
public void testBark() {
// The argument to be tested should be called on a mocked class
// i.e. we need to test the "lifeQuote" argument passed onto "Util" method "shoutOut"
// therefore we should mock the Util class
Util utilMock = mock(Util.class);
Dog toby = new Dog(utilMock);
toby.bark();
// We need to create a captor to capture the argument
// In our case, the captured argument is of type String
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
// Verify that the captor is used in the mocked method
verify(utilMock).shoutOut(captor.capture());
// Retrieve the captured value
String updatedLifeQuote = captor.getValue();
// Assert if the value is as expected
assertEquals("I'm awesome", updatedLifeQuote);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment