Programming

Mockito : 개인 @Autowired 필드에 실제 객체 주입

procodes 2020. 5. 29. 23:27
반응형

Mockito : 개인 @Autowired 필드에 실제 객체 주입


Mockito @Mock@InjectMocks주석을 사용하여 Spring으로 주석이 달린 개인 필드에 종속성을 주입합니다 @Autowired.

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Mock
    private SomeService service;

    @InjectMocks
    private Demo demo;

    /* ... */
}

public class Demo {

    @Autowired
    private SomeService service;

    /* ... */
}

이제 실제 객체를 @Autowiredsetter없이 개인 필드에 주입하고 싶습니다 . 이것이 가능합니까 아니면 메커니즘은 Mocks 주입에만 국한됩니까?


@Spy주석 사용

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Spy
    private SomeService service = new RealServiceImpl();

    @InjectMocks
    private Demo demo;

    /* ... */
}

Mockito는 주석으로 주석이 달린 인스턴스에 삽입 될 잠재적 후보로서 모든 필드 @Mock또는 @Spy주석을 고려합니다 @InjectMocks. 위의 경우 'RealServiceImpl'인스턴스는 '데모'에 주입됩니다.

자세한 내용은

모키 토 홈

@스파이

@모조품


@Dev Blanked 응답 추가에서 Spring이 만든 기존 Bean을 사용하려는 경우 코드를 다음과 같이 수정할 수 있습니다.

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {

    @Inject
    private ApplicationContext ctx;

    @Spy
    private SomeService service;

    @InjectMocks
    private Demo demo;

    @Before
    public void setUp(){
        service = ctx.getBean(SomeService.class);
    }

    /* ... */
}

이렇게하면 테스트를 수행하기 위해 코드를 변경하거나 다른 생성자를 추가 할 필요가 없습니다.


Mockito는 DI 프레임 워크가 아니며 DI 프레임 워크조차도 필드 주입보다 생성자 주입을 권장합니다.
따라서 테스트중인 클래스의 종속성을 설정하기 위해 생성자를 선언하면됩니다.

@Mock
private SomeService serviceMock;

private Demo demo;

/* ... */
@BeforeEach
public void beforeEach(){
   demo = new Demo(serviceMock);
}

Using Mockito spy for the general case is a terrible advise. It makes the test class brittle, not straight and error prone : What is really mocked ? What is really tested ?
@InjectMocks and @Spy also hurts the overall design since it encourages bloated classes and mixed responsibilities in the classes.
Please read the spy() javadoc before using that blindly (emphasis is not mine) :

Creates a spy of the real object. The spy calls real methods unless they are stubbed. Real spies should be used carefully and occasionally, for example when dealing with legacy code.

As usual you are going to read the partial mock warning: Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.

However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.

참고URL : https://stackoverflow.com/questions/20270391/mockito-inject-real-objects-into-private-autowired-fields

반응형