Q:

Spring @Value field injection in mockito

@Service
public class MyClass {

...

  @Autowired
  public MyClass(@Value("${my.value}") String myValue)  {
      ...
  }

...
}

My Test class:
public class MyTest {

    @Mock(name = "solrServer")
    private SolrServer solrServer;

    @InjectMocks
    private MyClass myClassMock;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    ....
}

I have an exeption as follow:

org.mockito.exceptions.base.MockitoException:  Cannot instantiate
  @InjectMocks field named 'myClassMock' of type 'class
  mypackage.MyClass'. You haven't provided the
  instance at field declaration so I tried to construct the instance.
  However the constructor or the initialization block threw an exception
  : null
at mypackage.MyTest.setUp(MyTest.java:46)
      ...
  Caused by: java.lang.NullPointerException
  ...

How to inject @Value field from MyTest class, and fixed it?

A:

You can do it within the @Before annotated method by making an instance of your class manually, like so:
public class MyTest {

    @Mock(name = "solrServer")
    private SolrServer solrServer;

    @InjectMocks
    private MyClass myClassMock;

    @Before
    public void setUp() {
        myClassMock = new MyClass("value you need");
        MockitoAnnotations.initMocks(this);
    }

    @Test
    ....

}

