@Mock, @MockBean 및 Mockito.mock ()의 차이점
테스트를 만들고 종속성을 조롱 할 때이 세 가지 접근 방식의 차이점은 무엇입니까?
@MockBean :
@MockBean MyService myservice;
@모조품:
@Mock MyService myservice;
Mockito.mock ()
MyService myservice = Mockito.mock(MyService.class);
Plain Mockito 라이브러리
import org.mockito.Mock;
...
@Mock
MyService myservice;
과
import org.mockito.Mockito;
...
MyService myservice = Mockito.mock(MyService.class);
Mockito 라이브러리에서 가져 오며 기능적으로 동일합니다.
클래스 또는 인터페이스를 모의하고 그에 대한 동작을 기록하고 확인할 수 있습니다.
주석을 사용하는 방법은 더 짧아서 선호되고 종종 선호됩니다.
테스트 실행 중에 Mockito 주석을 활성화하려면 MockitoAnnotations.initMocks(this)
정적 메서드를 호출해야합니다.
테스트 간의 부작용을 피하려면 각 테스트 실행 전에 수행하는 것이 좋습니다.
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
Mockito 주석을 활성화하는 또 다른 방법 은이 작업을 수행 @RunWith
하는 MockitoJUnitRunner
을 지정하여 테스트 클래스에 주석을 추가하는 것입니다.
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public MyClassTest{...}
Mockito 라이브러리를 래핑하는 Spring Boot 라이브러리
이것은 실제로 Spring Boot 클래스입니다 .
import org.springframework.boot.test.mock.mockito.MockBean;
...
@MockBean
MyService myservice;
클래스는 spring-boot-test
라이브러리에 포함되어 있습니다.
Mockito 모의를 Spring에 추가 할 수 있습니다 ApplicationContext
.
선언 된 클래스와 호환되는 빈이 컨텍스트에 존재 하면 모의 객체로 대체 합니다.
그렇지 않은 경우 컨텍스트에 모의 객체를 빈으로 추가 합니다.
Javadoc 참조 :
Spring ApplicationContext에 모의를 추가하는 데 사용할 수있는 어노테이션.
...
컨텍스트에 정의 된 동일한 유형의 기존 단일 Bean이 mock으로 대체되면 기존 Bean이 정의되지 않은 경우 새 Bean이 추가됩니다.
classic / plain Mockito를 사용할 때와 @MockBean
Spring Boot에서 사용할 때 ?
단위 테스트는 다른 구성 요소와 분리 된 상태로 구성 요소를 테스트하도록 설계되었으며 단위 테스트에는 또한 요구 사항이 있습니다. 이러한 테스트는 개발자 컴퓨터에서 매일 수십 번 실행될 수 있으므로 실행 시간 측면에서 가능한 한 빠릅니다.
결과적으로 다음은 간단한 지침입니다.
Spring Boot 컨테이너의 종속성이 필요하지 않은 테스트를 작성할 때 클래식 / 일반 Mockito가 따르는 방법입니다. 빠르고 테스트 된 구성 요소의 격리를 선호합니다.
테스트는 봄 부팅 컨테이너에 의존 할 필요가있는 경우 그리고 당신은 또한 추가하거나 컨테이너 콩의 모의 한하려면 : @MockBean
봄 부팅에서 방법입니다.
Spring Boot의 일반적인 사용법 @MockBean
@WebMvcTest
(웹 테스트 슬라이스) 주석이 달린 테스트 클래스를 작성합니다 .
The Spring Boot documentation summarizes that very well :
Often
@WebMvcTest
will be limited to a single controller and used in combination with@MockBean
to provide mock implementations for required collaborators.
Here is an example :
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebMvcTest(FooController.class)
public class FooControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private FooService fooServiceMock;
@Test
public void testExample() throws Exception {
Foo mockedFoo = new Foo("one", "two");
Mockito.when(fooServiceMock.get(1))
.thenReturn(mockedFoo);
mvc.perform(get("foos/1")
.accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andExpect(content().string("one two"));
}
}
At the end its easy to explain. If you just look into the javadocs of the annotations you will see the differents:
@Mock: (org.mockito.Mock
)
Mark a field as a mock.
- Allows shorthand mock creation.
- Minimizes repetitive mock creation code.
- Makes the test class more readable.
- Makes the verification error easier to read because the field name is used to identify the mock.
@MockBean: (org.springframework.boot.test.mock.mockito.MockBean
)
Annotation that can be used to add mocks to a Spring ApplicationContext. Can be used as a class level annotation or on fields in either
@Configuration
classes, or test classes that are@RunWith
the SpringRunner.Mocks can be registered by type or by bean name. Any existing single bean of the same type defined in the context will be replaced by the mock, if no existing bean is defined a new one will be added.
When
@MockBean
is used on a field, as well as being registered in the application context, the mock will also be injected into the field.
Mockito.mock()
Its just the representation of a
@Mock
.
참고URL : https://stackoverflow.com/questions/44200720/difference-between-mock-mockbean-and-mockito-mock
'Programing' 카테고리의 다른 글
Swift 프로그래밍 : 저장된 속성의 getter / setter (0) | 2020.08.16 |
---|---|
.NET 용 SFTP 라이브러리 (0) | 2020.08.16 |
Adb 기기에서 내 휴대 전화를 찾을 수 없음 (0) | 2020.08.16 |
초기 버전으로 무엇을 사용해야합니까? (0) | 2020.08.16 |
xtable을 사용할 때 data.frame 행 이름 제거 (0) | 2020.08.16 |