Mockテスト
2015 ワード
1.必要なjarパッケージ
mockito-all-1.8.5.JArとjunit-4.8.1.jar
2.Test.JAvaは以下の通りです
mockito-all-1.8.5.JArとjunit-4.8.1.jar
2.Test.JAvaは以下の通りです
import static org.mockito.BDDMockito.*;
import javax.persistence.EntityTransaction;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import xx.domain.User;
import xx.domain.UserService;
public class Test {
private static final long EXPECTED_ID = 12345;
@Mock
private UserService userService;
@Mock
private EntityTransaction mockTransaction;
private User user;
private User result;
@Before
public void init() {
MockitoAnnotations.initMocks(this);
user = new User();
user.setId(EXPECTED_ID);
testInstance = new UserServiceImpl(mockService);
}
@Test
public void testSearchById() {
givenUserToSearch();
whenSearch();
thenVerifyResult();
}
private void whenSearch() {
result = testInstance.searchById(12345);
}
@Test
public void testSaveUser() {
givenClaimApplicationToSave();
whenSave();
thenVerifyResult();
}
private void givenUserToSearch() {
given(mockService.find(EXPECTED_ID)).willReturn(user);
}
private void thenVerifyResult() {
Assert.assertEquals(EXPECTED_ID, result.getId());
}
private void whenSave() {
result = testInstance.saveUser(user);
}
private void givenUserToSave() {
given(mockService.startNewTransaction()).willReturn(mockTransaction);
given(mockService.saveUser(user)).willReturn(user);
}
}