[JUnit & Mockito] Return Multiple Values & Argument Matchers

μ›μ•Œλ ‰μŠ€Β·2020λ…„ 8μ›” 28일
0

JUnit & Mockito

λͺ©λ‘ 보기
3/9
post-thumbnail

πŸš€ Return Multiple Values

보톡은 when() κ³Ό thenReturn() 을 μ‚¬μš©ν•  λ•Œ

private final List<String> mock = mock(List.class);

@Test
public void returnSingleValue() {
    when(mock.size()).thenReturn(5);
    assertEquals(5, mock.size());
}

이런 μ‹μœΌλ‘œ ν•˜λ‚˜μ˜ κ°’λ§Œμ„ λ¦¬ν„΄ν•˜λŠ” ν˜•νƒœλ‘œ Mock Object λ₯Ό μ‚¬μš©ν•˜μ§€λ§Œ, μ—°μ†μ μœΌλ‘œ 리턴값을 확인을 ν•  λ•ŒλŠ” λ‹€μŒκ³Ό 같이 thenReturn() 을 ν•„μš”ν•œ 만큼 더 뢙이면 λ©λ‹ˆλ‹€.

@Test
public void returnMultipleValues() {
    when(mock.size()).thenReturn(5).thenReturn(10);
    assertEquals(5, mock.size());
    assertEquals(10, mock.size());
}

πŸš€ Argument Matchers

λ‹€μŒμœΌλ‘œλŠ” ν•΄λ‹Ή Mock Object에 νŒŒλΌλ―Έν„°μ™€ ν•¨κ»˜ λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•  λ•Œμ—λŠ” λ‹€μŒκ³Ό 같이 μž‘μ„±ν•˜μ‹œλ©΄ λ˜λŠ”λ°, λ§Œμ•½ 정해놓은 νŒŒλΌλ―Έν„°λ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  Mock Objectλ₯Ό μ‚¬μš©ν•˜κ²Œ 되면 μ „λ‹¬ν•œ 값에 ν•΄λ‹Ήν•˜λŠ” λ””ν΄νŠΈκ°’μ΄ λ°˜ν™˜λ©λ‹ˆλ‹€.

@Test
public void returnWithParameters() {
    when(mock.get(0)).thenReturn("in28minutes");
    assertEquals("in28minutes", mock.get(0));
    assertNull(mock.get(1));
}

그리고 μœ„μ™€ 같이 값을 ν•˜λ“œ μ½”λ”©ν•˜μ§€ μ•Šκ³  λ™μ μœΌλ‘œ νŒŒλΌλ―Έν„° 값을 μ„€μ •ν•˜κ³  μ‹ΆμœΌμ‹œλ‹€λ©΄, Mockito의 Argument Matchers 클래슀λ₯Ό μ‚¬μš©ν•˜μ‹œλ©΄ λ©λ‹ˆλ‹€.

@Test
public void returnWithGenericParameters() {
    when(mock.get(anyInt())).thenReturn("in28minutes");
    assertEquals("in28minutes", mock.get(0));
    assertEquals("in28minutes", mock.get(1));
}
profile
Alex's Develog πŸ€”

0개의 λŒ“κΈ€