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;
/* ... */
}
이제 실제 객체를 @Autowired
setter없이 개인 필드에 주입하고 싶습니다 . 이것이 가능합니까 아니면 메커니즘은 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.
'Programming' 카테고리의 다른 글
일반 유형 또는 메소드 'System.Nullable'에서 매개 변수 T로 사용하려면 'string'유형은 널 입력 불가능 유형이어야합니다. (0) | 2020.05.29 |
---|---|
파이썬은 해석되거나 컴파일됩니까, 아니면 둘 다입니까? (0) | 2020.05.29 |
Ruby on Rails 프로덕션 로그 회전 (0) | 2020.05.29 |
git diff를 사용하여 두 개의 스프레드 시트로 읽을 수있는 diff를 만들려면 어떻게합니까? (0) | 2020.05.29 |
외래 키 제약 조건으로 인해 사이클이나 다중 캐스케이드 경로가 발생할 수 있습니까? (0) | 2020.05.29 |