programing

Junit 5(스프링 부트 포함):@ExtendWithSpring 또는 Mockito를 언제 사용해야 합니까?

copyandpastes 2023. 8. 14. 23:40
반응형

Junit 5(스프링 부트 포함):@ExtendWithSpring 또는 Mockito를 언제 사용해야 합니까?

모든 구체적인 단위 시험 수업이 확장되는 다음과 같은 추상 단위 시험 수업이 있습니다.

@ExtendWith(SpringExtension.class)
//@ExtendWith(MockitoExtension.class)
@SpringBootTest(
    classes = PokerApplication.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
public abstract class AbstractUnitTests {

    @MockBean
    public RoundService roundService;

    @MockBean
    public RoundRepository roundRepository;
}

을 사용하는 것의 차이점은 무엇입니까?@ExtendWith(SpringExtension.class)또는@ExtendWith(MockitoExtension.class)?

두 주석 중 하나를 사용해도 아무런 차이가 없는 것 같고 두 주석 모두 내 코드에서 각각 작동하므로 Junit5를 사용할 수 있습니다.그렇다면 왜 둘 다 효과가 있을까요?

콘크리트 시험 등급:

    @DisplayName("Test RoundService")
    public class RoundsServiceTest extends AbstractUnitTests {

        private static String STUB_USER_ID = "user3";

        // class under test
        @InjectMocks
        RoundService roundService;

        private Round round;

        private ObjectId objectId;

        @BeforeEach //note this replaces the junit 4 @Before
        public void setUp() {

            initMocks(this);
            round = Mocks.round();
            objectId = Mocks.objectId();
        }

        @DisplayName("Test RoundService.getAllRoundsByUserId()")
        @Test
        public void shouldGetRoundsByUserId() {

            // setup
            given(roundRepository.findByUserId(anyString())).willReturn(Collections.singletonList(round));

            // call method under test
            List<Round> rounds = roundService.getRoundsByUserId(STUB_USER_ID);

            // asserts
            assertNotNull(rounds);
            assertEquals(1, rounds.size());
            assertEquals("user3", rounds.get(0).userId());
        }
}

관련 Build.gradle 섹션:

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.2.2.RELEASE'

    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'

    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    implementation 'junit:junit:4.12'
}

test {
    useJUnitPlatform()
}

Junit 확장이란 무엇입니까?

Junit 5 확장의 목적은 테스트 클래스 또는 메서드의 동작을 확장하는 것입니다.

원천

Junit 5 확장 모델 및@ExtendWith주석:여기

SpringExtension

SpringExtension은 SpringTestContext Framework를 Junit 5의 Jupiter 프로그래밍 모델에 통합합니다.

public class SpringExtension
extends Object
implements BeforeAllCallback, AfterAllCallback, TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, BeforeTestExecutionCallback, AfterTestExecutionCallback, ParameterResolver{..}

MockitoExtension

이 확장은 JUNit4 Mockito와 동등한 JUNit 목성입니다.준트러너

public class MockitoExtension
extends java.lang.Object
implements BeforeEachCallback, AfterEachCallback, ParameterResolver{..}

보다시피,SpringExtension보다 훨씬 더 많은 확장 구현MockitoExtension.

또한 메타 주석을 달았습니다.@ExtendWith(SpringExtension.class)그리고 그 말은 당신의 테스트가 매번 연장된다는 것을 의미합니다.SpringExtensionSpring 테스트 프레임워크 주석이며 함께 사용됩니다@MockBean.@ExtendWith(SpringExtension.class)

차이를 관찰하려면 다음을 수행합니다.

ExtendWith오직.MockitoExtension

@ExtendWith(MockitoExtension.class)
class TestServiceTest {

    @MockBean
    TestService service;

    @Test
    void test() {
        assertNotNull(service); // Test will fail
    }

}

ExtendWith오직.SpringExtension

@ExtendWith(SpringExtension.class)
class TestServiceTest {

    @MockBean
    TestService service;

    @Test
    void test() {
        assertNotNull(service); // Test succeeds
    }

}

ExtendWith둘 다SpringExtension그리고.MockitoExtension

@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
class TestServiceTest {

    @MockBean
    TestService service;

    @Test
    void test() {
        assertNotNull(service); // Test succeeds
    }

}

두 가지 모두 당신의 경우에 효과가 있습니다.@SpringBootTest설명된 대로 테스트 클래스에 대한 주석.

질문에 답하기: 사용 시기@ExtendWith봄 아니면 모키토? ,

테스트에 스프링 테스트 컨텍스트가 필요한 경우(자동 배선을 위해)@MockBean) JUNit 5의 Jupit 프로그래밍 모델 사용과 함께@ExtendWith(SpringExtension.class)테스트 실행 청취자를 통해 Mockito 주석도 지원합니다.

테스트가 Mockito를 사용하고 Junit 5의 Jupiter 프로그래밍 모델 지원이 필요할 때 사용합니다.@ExtendWith(MockitoExtension.class)

이것이 도움이 되길 바랍니다.

@ExtendWith(SpringExtension.class) 또는 @SpringBootTest를 언제 사용해야 합니까?

  • 통합 테스트를 사용하는 경우 -@SpringBoot주석 테스트 - 또는 슬라이스 테스트 - @xxx 주석 테스트 - 언급된 주석에 포함되어 있으므로 @ExtendWith(SpringExtension.class) 주석이 필요하지 않습니다.

  • @ConfigurationProperties, @Service, @Component 주석이 달린 클래스를 테스트하는 경우(슬라이스 테스트 사례에 정의되지 않음 - 참조:SpringBoot 참조 문서 테스트/자동 구성/SPLETED 테스트 항목 - @SpringBootTest 대신 @ExtendWith(SpringExtension.class)를 사용할 수 있습니다.

관찰:@ExtendWith(SpringExtension.class)를 사용하는 테스트가 @SpringBootTest와 동일한 테스트보다 빠를 것으로 예상됩니다.제가 이클립스에서 테스트를 수행했을 때 저는 그 반대를 관찰했습니다.

추가 정보 추가하기저도 최근에 알게 된 사실인데요, 만약 당신이@Mock이 달린 은 테트클 종속달로 표시됩니다.MockitoExtension그리고 당신은 사용하려고 노력합니다.Mockito.when(mockedDependency.methodName())@BeforeAll설정 방법, 그러면 당신은 그것을 얻는 것입니다.NullPointer당신의 조롱당한 의존성 때문에.

하지만 당신이 변한다면,MockitoExtensionSpringExtension잘 작동합니다.와 같이 보입니다.SpringExtension조롱당한 콩은 이전에 초기화되었습니다(이전).JUnit 칭런@BeforeAll방법) 제대로 작동해야 하는 것처럼.

언급URL : https://stackoverflow.com/questions/61433806/junit-5-with-spring-boot-when-to-use-extendwith-spring-or-mockito

반응형