본문 바로가기
Programming & Language/Spring

@Autowired와 @InjectMocks 를 같이 쓰고 싶을 때

by 몽글구름 2022. 7. 4.
public class A () {
    @Autowired
    private B b;

    @Autowired
    private C c;

    @Autowired
    private D d;
}

다음과 같은 코드에서 D는 원래의 빈을 사용하고 B와 C를 모킹하고 싶다고 가정해보자.

 

해당 경우에는 

public class aTest () {
    @Mock
    private B b;

    @Mock
    private C c;

    @Autowired
    @InjectMocks
    private A a;
}

이렇게 사용하는 것이 아닌

 

public class aTest () {
    @MockBean
    private B b;

    @MockBean
    private C c;

    @Autowired
    private A a;
}

이렇게 사용해야 한다.

 

 

https://stackoverflow.com/questions/34067956/how-to-use-injectmocks-along-with-autowired-annotation-in-junit

 

How to use @InjectMocks along with @Autowired annotation in Junit

I have a class A which is using 3 differnt classes with autowiring public class A () { @Autowired private B b; @Autowired private C c; @Autowired private D d; } While

stackoverflow.com

 

댓글