sourcetip

@Autowired Bean은 Spring Boot Unit 테스트에서 NULL입니다.

fileupload 2023. 3. 14. 21:50
반응형

@Autowired Bean은 Spring Boot Unit 테스트에서 NULL입니다.

처음입니다.JUnit테스트 자동화를 목표로 하고 있습니다.이것은 Spring Boot 어플리케이션입니다.XML 기반 구성 대신 Java 기반 주석 스타일을 사용했습니다.

사용자의 입력에 따라 응답을 검색하는 메서드를 테스트하고 싶은 테스트 클래스가 있습니다.

테스트 클래스:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest(){

  @Autowired
  private SampleClass sampleClass;

  @Test
  public void testInput(){

  String sampleInput = "hi";

  String actualResponse = sampleClass.retrieveResponse(sampleInput);

  assertEquals("You typed hi", actualResponse);

  }
}

'Sample Class' 안에 이렇게 된 콩이 있어요.

@Autowired
private OtherSampleClass sampleBean;

"OtherSampleClass"에서는 다음과 같은 메서드에 주석을 달았습니다.

@Bean(name = "sampleBean")
public void someMethod(){
....
}

문제가 되고 있는 것은, 이 테스트의 실행시에, 이 테스트의 실행시에,@RunWith그리고.@SpringBootTest테스트 실행 시 주석 내 변수 주석@Autowired무효입니다.그리고 이러한 주석을 사용하여 테스트를 실행하려고 하면 Run With & Spring Boot테스트하고 나면

BeanCreation으로 인해 발생한 InvalidStateException예외:"sampleBean" 이름의 콩을 생성하는 동안 오류가 발생하여 BeanInstantiation으로 인해 애플리케이션 컨텍스트를 로드하지 못했습니다.예외.

사용자처럼 사용하려고 하면 코드가 '적절하게' 작동하기 때문에 항상 이 방법으로 테스트할 수 있지만 자동 테스트가 프로그램의 지속 시간에 도움이 될 것이라고 생각합니다.

이 문제를 해결하기 위해 Spring Boot Testing Docs를 사용하고 있습니다.

다음의 설정이 유효합니다.

파일:build.gradle

testCompile("junit:junit:4.12")
testCompile("org.springframework.boot:spring-boot-starter-test")

파일:MYServiceTest.java

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest(classes = Application.class,
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
public class MYServiceTest {

    @Autowired
    private MYService myService;

    @Test
    public void test_method() {
        myService.run();
    }
}

스프링은 가능한 한 유닛 테스트에 참여하지 않는 것이 좋습니다.콩을 자동 배선하는 대신 일반 객체로 생성하십시오.

OtherSampleClass otherSampleClass = mock(OtherSampleClass.class);
SampleClass sampleClass = new SampleClass(otherSampleClass);

그러나 이를 위해서는 테스트 가능성을 향상시키는 필드 주입 대신 생성자 주입을 사용해야 합니다.

이것을 치환하다

@Autowired
private OtherSampleClass sampleBean;

이와 함께.

private OtherSampleClass sampleBean;

@Autowired
public SampleClass(OtherSampleClass sampleBean){
    this.sampleBean = sampleBean;
}

다른 코드의 예에 대해서는, 이 답을 봐 주세요.

주입 불필요(@Autowired private SampleClass sampleClass;테스트 중인 실제 클래스를 삭제하고 Spring Boot을 삭제합니다.주석 테스트,
스프링 부트통합 테스트 사례에 사용되는 테스트 주석.
다음 코드를 찾으십시오.

@RunWith(SpringRunner.class)
public class SampleTest(){

  private SampleClass sampleClass;

언급URL : https://stackoverflow.com/questions/48113464/autowired-bean-is-null-in-spring-boot-unit-test

반응형