2
일반적으로 Spring으로 관리되는 일부 코드에 대해 JUnit 테스트를 작성하려고합니다. 때 다른 클래스 나는 경우에 실행Mockito 대 @Configurable
@RunWith(PowerMockRunner.class)
public class ATest {
@Spy MyService service = new MyService();
@Before void initMocks() { MockitoAnnotations.initMocks(this); }
@Test void test() {
@InjectMocks A a = new A(); // injects service into A
a.callA();
//assert things
}
}
하지만 지금 :
@Configurable
public class A {
@Autowired MyService service;
public void callA() { service.doServiceThings(); }
}
이 같은 Mockito 및 PowerMock를 사용하여이 클래스에 대한 테스트를 작성할 수 있습니다
의 내가이 있다고 가정 해 봅시다 A의 인스턴스를 구성합니다 :
public class B {
public void doSomething() {
A a = new A(); // service is injected by Spring
a.callA();
}
}
어떻게 A 인스턴스에 서비스를 삽입합니까? B 방법 안에서 만들었습니까?
@RunWith(PowerMockRunner.class)
public class BTest {
@Spy MyService service = new MyService();
@Before void initMocks() { MockitoAnnotations.initMocks(this); }
@Test testDoSomething() {
B b = new B();
// is there a way to cause service to be injected when the method calls new A()?
b.doSomething();
// assert things
}
}
쉽게는 아니지만 필드 주입에 대한 훌륭한 논거입니다. 아마도 Spring 테스트 컨텍스트를 사용해야 할 것이다. – chrylis