Created
March 10, 2011 14:41
-
-
Save searls/864185 to your computer and use it in GitHub Desktop.
An example of stubbing with Mockito (with TestNG)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pillartechnology.mail; | |
public class AddressInputQueue { | |
public String next() { | |
return null; //TODO: not implemented yet. | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pillartechnology.mail; | |
import static java.util.Arrays.*; | |
import java.util.List; | |
public class AddressSplitter { | |
private AddressInputQueue addressInputQueue; | |
public List<String> split() { | |
return asList(addressInputQueue.next().split(",")); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.pillartechnology.mail; | |
import static org.hamcrest.MatcherAssert.*; | |
import static org.hamcrest.Matchers.*; | |
import static org.mockito.Mockito.*; | |
import java.util.List; | |
import org.mockito.InjectMocks; | |
import org.mockito.Mock; | |
import org.mockito.MockitoAnnotations; | |
import org.testng.annotations.BeforeMethod; | |
import org.testng.annotations.Test; | |
public class AddressSplitterTest { | |
@InjectMocks private AddressSplitter subject = new AddressSplitter(); | |
@Mock private AddressInputQueue addressInputQueue; | |
@BeforeMethod(alwaysRun=true) | |
public void injectDoubles() { | |
MockitoAnnotations.initMocks(this); //This could be pulled up into a shared base class | |
} | |
@Test | |
public void splitsAddressesByComma() { | |
when(addressInputQueue.next()).thenReturn("[email protected],[email protected]"); | |
List<String> result = subject.split(); | |
assertThat(result,hasItems("[email protected]","[email protected]")); | |
} | |
} |
Thank you!
Thanks, very helpful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When I was using mockito without @mock, the verify() calls would count up for every @test annotated method. The only wayw to fix this problem was to use this gist, or new up the mock in the @BeforeMethod (which didn't seem reasonable). I like this default behavior better, where the mock isn't expected to persist state from previous tests.