Situation: I have service implementation class annotated with @Service with access to properties file.
@Service("myService")
public class MySystemServiceImpl implements SystemService{
@Resource
private Properties appProperties;
}
Properties object is configured through config-file. applicationContext.xml
<util:properties id="appProperties" location="classpath:application.properties"/>
I want to test some methods of this implementation.
Question:How to access MySystemServiceImpl-object from test class in such way that Properties appProperties will be initialized properly?
public class MySystemServiceImplTest {
//HOW TO INITIALIZE PROPERLY THROUGH SPRING?
MySystemServiceImpl testSubject;
@Test
public void methodToTest(){
Assert.assertNotNull(testSubject.methodToTest());
}
}
I can’t simple create new MySystemServiceImpl – than methods that use appProperties throws NullPointerException. And I can’t directly inject properties in the object – there is no appropriate setter-method.
Just put correct steps here (thanks to @NimChimpsky for answer):
-
I copied application.properties under test/resources dir.
-
I copied applicationContext.xml under test/resources dir. In application context I add new bean (definition of application properties is already here):
<bean id="testSubject" class="com.package.MySystemServiceImpl"> -
I modified test class in such way:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"/applicationContext.xml"}) public class MySystemServiceImplTest { @Autowired MySystemServiceImpl testSubject; } -
And this make the trick – now in my test class fully functional object is available
Alternatively, to do an integration test I do this.
Then use the service as you would normally. Add the app context to your test/resources directory