Injecting @Autowired private field during testing

后端 未结 6 1058
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-29 17:08

I have a component setup that is essentially a launcher for an application. It is configured like so:

@Component
public class MyLauncher {
    @Autowired
            


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 17:41

    The accepted answer (use MockitoJUnitRunner and @InjectMocks) is great. But if you want something a little more lightweight (no special JUnit runner), and less "magical" (more transparent) especially for occasional use, you could just set the private fields directly using introspection.

    If you use Spring, you already have a utility class for this : org.springframework.test.util.ReflectionTestUtils

    The use is quite straightforward :

    ReflectionTestUtils.setField(myLauncher, "myService", myService);
    

    The first argument is your target bean, the second is the name of the (usually private) field, and the last is the value to inject.

    If you don't use Spring, it is quite trivial to implement such a utility method. Here is the code I used before I found this Spring class :

    public static void setPrivateField(Object target, String fieldName, Object value){
            try{
                Field privateField = target.getClass().getDeclaredField(fieldName);
                privateField.setAccessible(true);
                privateField.set(target, value);
            }catch(Exception e){
                throw new RuntimeException(e);
            }
        }
    

提交回复
热议问题