Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
引数を使ってスタブの返値を決める
public enum Gender {
MALE, FEMALE;
}
public interface GenderDetector {
Gender detect(String name);
}
public class Honorific {
GenderDetector detector;
Honorific(GenderDetector detector) {
this.detector = detector;
}
public String makeFor(String name) {
Gender gender = this.detector.detect(name);
if (gender == Gender.MALE) {
return "くん";
} else if (gender == Gender.FEMALE) {
return "ちゃん";
} else {
return null;
}
}
}
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
@RunWith(MockitoJUnitRunner.class)
public class MockitoSample {
private static final Map<String, Gender> GENDER_MAP =
new HashMap<String, Gender>() {{
put("大槻ケンヂ", Gender.MALE);
put("荻野由佳", Gender.FEMALE);
put("ピーター", null);
}};
@Mock
private GenderDetector genderDetectorMock;
private Honorific tested;
@Before
public void setUp() {
tested = new Honorific(genderDetectorMock);
}
@Test
public void 引数を使って返値を返す() throws Exception {
doAnswer(invocation ->
GENDER_MAP.get(invocation.getArguments()[0]))
.when(genderDetectorMock).detect(anyString());
Assert.assertEquals("くん", tested.makeFor("大槻ケンヂ"));
Assert.assertEquals("ちゃん", tested.makeFor("荻野由佳"));
Assert.assertEquals(null, tested.makeFor("ピーター"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment