Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring value injection in mockito

I'm trying to write test class for the following method

public class CustomServiceImpl implements CustomService {
    @Value("#{myProp['custom.url']}")
    private String url;
    @Autowire
    private DataService dataService;

I'm using the injected url value in one of the methods in the class. To test this i've written a junit class

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public CustomServiceTest{
    private CustomService customService;
    @Mock
    private DataService dataService;
    @Before
    public void setup() {
        customService = new CustomServiceImpl();
        Setter.set(customService, "dataService", dataService);
    }    
    ...
}

public class Setter {
    public static void set(Object obj, String fieldName, Object value) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }
}

In applicationContext-test.xml I'm loading the property file using

    <util:properties id="myProp" location="myProp.properties"/>

But the url value is not getting loaded in the CustomService on running the test. I was wondering if there is anyway to get this done.

Thanks

like image 839
rohit Avatar asked Sep 06 '25 03:09

rohit


1 Answers

import org.springframework.test.util.ReflectionTestUtils;

@RunWith(MockitoJUnitRunner.class)
public CustomServiceTest{

@InjectMocks
private CustomServiceImpl customService;

@Mock
private DataService dataService;

@Before
public void setup() {
    ReflectionTestUtils.setField(customService, "url", "http://someurl");
}    
...
}
like image 67
Robert Hutto Avatar answered Sep 08 '25 17:09

Robert Hutto