Created
August 9, 2018 16:59
-
-
Save ytnk531/532cfa8fc7f5675c1097d884a02b426f to your computer and use it in GitHub Desktop.
引数を使ってスタブの返値を決める
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
public enum Gender { | |
MALE, FEMALE; | |
} |
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
public interface GenderDetector { | |
Gender detect(String name); | |
} |
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
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; | |
} | |
} | |
} |
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
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