Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kuneo
Last active September 30, 2016 14:56
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 kuneo/d9c5c43c3b000e6d85a7e41d5c946f31 to your computer and use it in GitHub Desktop.
Save kuneo/d9c5c43c3b000e6d85a7e41d5c946f31 to your computer and use it in GitHub Desktop.
mockito説明用試験クラス
package kuneo.org.sample.mockito;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import javax.naming.AuthenticationException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
public class LoginServiceTest {
/**
* 試験対象クラスから呼び出す下位クラスをモック化する
*/
LoginRepository loginRepository = mock(LoginRepository.class);
/**
* 試験対象クラスにモックを注入する
*/
@InjectMocks
LoginService target = new LoginServiceImpl();
@Before
public void setup() {
// モックを有効にする
MockitoAnnotations.initMocks(this);
}
@Test
public void ログインできることを確認する() throws AuthenticationException {
// 期待値を生成
boolean expected = true;
// モックを設定
// whenでモック化するメソッドを指定する
// loginRepository#findHashPasswordを、任意の文字列を引数として呼び出した時、
// thenReturnで指定した文字列を返却するように指定する
when(loginRepository.findHashPassword(anyString())).thenReturn("ea416ed0759d46a8de58f63a59077499");
// 試験対象メソッド呼び出し
boolean actual = target.login("user", "password");
// 呼び出し結果比較
assertThat(expected, is(actual));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment