How to access Spring @Service object from jUnit test

前端 未结 2 384
无人及你
无人及你 2020-12-30 13:48

Situation: I have service implementation class annotated with @Service with access to properties file.

@Service(\"myService\")
public class          


        
相关标签:
2条回答
  • 2020-12-30 14:09

    Just use its constructor :

    MySystemServiceImpl testSubject = new MySystemServiceImpl();
    

    This is a unit test. A unit test tests a class in isolation from the other classes and from the infrastructure.

    If your class has dependencies over other interfaces, mock those interfaces and create the object with these mocks as argument. That's the whole point of dependency injection : being able to inject other, mock implementations inside an object in order to test this object easily.

    EDIT:

    You should provide a setter for your properties object, in order to be able to inject the properties you want for each of the unit tests. The injected properties could contain nominal values, extreme values, or incorrect values depending on what you want to test. Field injection is practical, but doesn't fit well with unit-testing. Constructor or setter injection should be preferred when unit-testing is used, because the main goal of dependency injection is precisely to be able to inject mock or specific dependencies in unit tests.

    0 讨论(0)
  • 2020-12-30 14:21

    Alternatively, to do an integration test I do this.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations={"/applicationContext-test.xml"})
    @Transactional
    public class MyTest {
    
        @Resource(name="myService")
        public IMyService myService;
    

    Then use the service as you would normally. Add the app context to your test/resources directory

    0 讨论(0)
提交回复
热议问题