@Autowired with JUnit tests

前端 未结 3 1660
情深已故
情深已故 2021-01-21 19:38

I´ve using JUnit but some tests have some issues, these tests have @Autowired annotation inside the Spring beans and when i reference them the beans that are @Autowired were alw

相关标签:
3条回答
  • 2021-01-21 20:05

    Looks to me like ParametersJCSCache is not a Spring managed bean. You need to make this a Spring bean and autowire it into the Manager

    @Service
            public class Manager implements IManager {
    
                    public boolean doSomething() throws Exception {
                         ParametersJCSCache parametersJCSCache = new ParametersJCSCache(); <-- You create a new (non Spring-managed) instance
                         String paramValue = parametersJCSCache.getParameter("XPTO");
                         ...
                    }
            }
    

    Change to:

    @Service
    public class Manager implements IManager {
    
          @Autowired
          private ParametersJCSCache  parametersJCSCache; 
    
            public boolean doSomething() throws Exception {
                 String paramValue = parametersJCSCache.getParameter("XPTO");
                 ...
            }
    }
    
    @Component
    public class ParametersJCSCache extends JCSCache {
    
          @Autowired
          private IParameterManager parameterManager;  //THIS IS NULL
    }
    
    0 讨论(0)
  • 2021-01-21 20:06

    Try running your unit tests with a spring runner instead.

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:config/applicationContext.xml",
                     "classpath:config/test-datasources.xml"})
    public class MyTest {
    
       @Autowired private IManager manager;
    
       @Test public void someTest() {
         assertNotNull(manager);
       }
    }
    

    It will load the config only once and when needed, and it will autowire your junit class

    0 讨论(0)
  • 2021-01-21 20:08

    I've finally found a solution to my problem. Find this post SpringBeanAutowiringSupport does not inject beans in jUnit tests and do something like this the JUnit tests works.

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