DevEnjoy

One Step Closer

Mock

Spring @Mock, @Mockbean, @InjectMock

2018년 4월 17일 by YongPwi Leave a Comment

@Mock : (org.mockito.Mock)
import org.mockito.Mockito;
…
MyService myservice = Mockito.mock(MyService.class);

mockito에 포함

Mock 객체를 생성한다.

@Mockbean : (org.springframework.boot.test.mock.mockito.MockBean)

Spring boot test에 포함

Spirng ApplicationContext에 Mockito mock 객체를 추가 할 수 있다. Mock은 type이나 bean 이름별로 등록 할 수 있다. ApplicationContext에 정의 된 동일한 type의 bean이 존재하면 Mockito mock으로 선언한 mock bean으로 대체된다. 존재하지 않는 경우는 새 bean이 추가된다.

@InjectMock
class의 instance를 생성하고 @Mock(도는 @Spy) annotation으로 생성된 mock instance를 class의 instance에 주입한다. 이 mock instance를 초기화하고 주입하려면 @RunWith (MockitoJUnitRunner.class) 또는 Mockito.initMocks (this)를 사용해야한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RunWith(SpringRunner.class)
public class UserServiceTest {

    @InjectMocks
    UserService userService;

    @Mock
    UserRepository userRepository;

    // userRepository는 userService에 주입된다.
    // 하위 코드 같은 관계를 가지고 있다.

    private UserRepository userRepository

    public UserService(UserRepository userRepository){
        this.userRepository = userRepository;
    }

}
Posted in: Java, Programing, Spring Tagged: InjectMock, Mock, Mockbean, Spring, Spring boot

Calendar

6월 2025
일 월 화 수 목 금 토
« 4월    
1234567
891011121314
15161718192021
22232425262728
2930  

Recent Posts

  • ubuntu bastion 설정
  • Spring Boot properties 암호화
  • Git Repository Bitbucket과 Issue Tracker Redmine 연동 설정
  • Spring Security 동일 session 제어
  • Spring @Mock, @Mockbean, @InjectMock

Recent Comments

  • pzotov (Ubuntu 14.04에서 Sonarqube 6.7.1 service 등록)
  • cours de theatre paris (AWS ELB와 Auto Scaling 연동, nginx)
  • bayern munich (IntelliJ EAP Font rendering)
  • camiseta del chelsea (OS X에서 APP 아이콘 변경)
  • cheap football shirts replica (jQuery Ajax에서 json Array 직렬화)

Copyright © [the-year] [site-link].

Powered by [wp-link] and [theme-link].