How do I mock an autowired @Value field in Spring with Mockito?

I’m using Spring 3.1.4.RELEASE and Mockito 1.9.5. In my Spring class I have:

@Value("#{myProps['default.url']}")
private String defaultUrl;

@Value("#{myProps['default.password']}")
private String defaultrPassword;

// ...

From my JUnit test, which I currently have set up like so:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "classpath:test-context.xml" })
public class MyTest 
{ 

I would like to mock a value for my “defaultUrl” field. Note that I don’t want to mock values for the other fields — I’d like to keep those as they are, only the “defaultUrl” field. Also note that I have no explicit “setter” methods (e.g. setDefaultUrl) in my class and I don’t want to create any just for the purposes of testing.

Given this, how can I mock a value for that one field?

8 Answers
8

Leave a Comment