2016-06-29 1 views
0

Я новичок в Spring, и я пытаюсь загрузить файл свойств с помощью Spring framework, я могу успешно загрузить все свойства из теста junit, но когда я пытаюсь реализовать модульного тестирования в качестве функции он бросает NPE-Использование Spring для загрузки файла свойств Java, демонстрирующего NPE

мой JUnit класс (который работает, как ожидалось)

@RunWith(SpringJUnit4ClassRunner.class) 
@ActiveProfiles(profiles = "test") 
@ContextConfiguration("classpath:spring/xml-config-context.xml") 
public class GlueTestPropertiesTest2 extends TestCase { 

    @Autowired 
    GenericEnv env; 

    @Autowired 
    WebPropertiesLoader wpl; 

    @Test 
    public void testAppProperties() { 

     System.out.println("Running MiniConfigSpringPropertiesTest ..."); 

     System.out.println("Environment  : " + env.toString()); 

     System.out.println("Database Properties: " + wpl.toString()); 
    } 

} 

мой класс реализации (который проявляет NPE):

@ActiveProfiles(profiles = "test") 
@ContextConfiguration("classpath:spring/xml-config-context.xml") 
public class GlueTestProperties { 

    @Autowired 
    GenericEnv env; 

    @Autowired 
    WebPropertiesLoader wpl; 

    public static void main(String[] args) { 
     GlueTestProperties gp = new GlueTestProperties(); 
     gp.callme(); 


    } 


    private void callme(){ 

System.out.println("Running ConfigSpringPropertiesTest ..."); 

     System.out.println("Environment  : " + env.toString()); 

     System.out.println("Database Properties: " + wpl.toString()); 
    } 
} 

WebPropertiesLoader боб:

@Component 
public class WebPropertiesLoader { 

    @Value("${bank.ease.login.url}") 
    public String easeLoginUrl; 

    @Value("${bank.browser.name}") 
    public String browserName; 

    @Value("${bank.browser.version}") 
    public String browserVersion; 

    @Value("${webdriver.chrome.driver}") 
    public String chromeDriver; 

    @Value("${webdriver.ie.driver}") 
    public String ieDriver; 

    @Value("${bank.web.feature.location}") 
    public String webFeatureLocation; 

    @Value("${bank.web.test.location}") 
    public String webTestLocation; 

    @Value("${bank.event.log}") 
    public String eventLog; 

    @Value("${bank.epoxy.backend}") 
    public String epoxyBackend; 

    @Value("${bank.epoxy.host}") 
    public String epoxyHost; 

    @Value("${bank.epoxy.port}") 
    public String epoxyPort; 

    @Value("${bank.epoxy.debug}") 
    public String epoxyDebug; 

    @Value("${bank.epoxy.implicitWait}") 
    public String epoxyImplicitWait; 

    @Value("${bank.epoxy.timeout}") 
    public String epoxyTimeOut; 

    @Value("${bank.epoxy.default.url}") 
    public String epoxyDefaultURL; 

    @Value("${bank.sassy.url}") 
    public String sassyUrl; 

    @Value("${bank.transite.url}") 
    public String transiteUrl; 

    @Value("${bank.transite.login.url}") 
    public String transiteLoginUrl; 


    public String getBrowserName() { 
     return browserName; 
    } 

    public String getBrowserVersion() { 
     return browserVersion; 
    } 

    public String getChromeDriver() { 
     return chromeDriver; 
    } 

    public String getEpoxyDefaultURL() { 
     return epoxyDefaultURL; 
    } 

    public String getSassyUrl() { 
     return sassyUrl; 
    } 

    public String getTransiteUrl() { 
     return transiteUrl; 
    } 

    public String getTransiteLoginUrl() { 
     return transiteLoginUrl; 
    } 

    public String getIeDriver() { 
     return ieDriver; 
    } 

    public String getWebFeatureLocation() { 
     return webFeatureLocation; 
    } 

    public String getWebTestLocation() { 
     return webTestLocation; 
    } 

    public String getEventLog() { 
     return eventLog; 
    } 

    public String getEpoxyBackend() { 
     return epoxyBackend; 
    } 

    public String getEpoxyHost() { 
     return epoxyHost; 
    } 

    public String getEpoxyPort() { 
     return epoxyPort; 
    } 

    public String getEpoxyDebug() { 
     return epoxyDebug; 
    } 

    public String getEpoxyImplicitWait() { 
     return epoxyImplicitWait; 
    } 

    public String getEpoxyTimeOut() { 
     return epoxyTimeOut; 
    } 


    public String getEaseLoginUrl() { 
     return easeLoginUrl; 
    } 

    @Override 
    public String toString() { 
     return "Ease application Default Properties [browserName=" + browserName + ", browserVersion=" + browserVersion 
       + ", chromeDriver=" + chromeDriver + ", ieDriver=" + ieDriver + ", webFeatureLocation=" 
       + webFeatureLocation + ", webTestLocation=" + webTestLocation + ", eventLog=" + eventLog 
       + ", epoxyBackend=" + epoxyBackend + ", epoxyHost=" + epoxyHost + ", epoxyPort=" + epoxyPort 
       + ", epoxyDebug=" + epoxyDebug + ", epoxyImplicitWait=" + epoxyImplicitWait + ", epoxyTimeOut=" 
       + epoxyTimeOut + ", epoxyDefaultURL=" + epoxyDefaultURL + ", easeLoginUrl=" + easeLoginUrl + "]"; 
    } 

} 

Test окр боб:

@Component 
public class TestEnv implements GenericEnv { 

    private String envName = "test"; 

    @Value("${profile.name}") 
    private String profileName; 

    public String getEnvName() { 
     return envName; 
    } 

    public void setEnvName(String envName) { 
     this.envName = envName; 
    } 

    public String getProfileName() { 
     return profileName; 
    } 

    public void setProfileName(String profileName) { 
     this.profileName = profileName; 
    } 

    @Override 
    public String toString() { 
     return "TestEnv [envName=" + envName + ", profileName=" + profileName 
       + "]"; 
    } 

} 

Контекст XML используется:

?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 

    <!-- scans for annotated classes in the com.company package --> 
    <context:component-scan base-package="com.glue.commons" /> 

    <!-- enables annotation based configuration --> 
    <!-- <context:annotation-config /> --> 

    <beans profile="dev"> 
     <!-- allows for ${} replacement in the spring xml configuration from the 
      application-default.properties, application-dev files on the classpath --> 
     <context:property-placeholder 
      location="classpath:properties/application-web-default.properties, classpath:properties/application-web-dev.properties" 
      ignore-unresolvable="true" /> 

     <!-- scans for annotated classes in the com.env.dev package --> 
     <context:component-scan base-package="com.glue.env.dev" /> 
    </beans> 

    <beans profile="test"> 
     <!-- allows for ${} replacement in the spring xml configuration from the 
      application-default.properties, application-test files on the classpath --> 
     <context:property-placeholder 
      location="classpath:properties/application-web-default.properties, classpath:properties/application-web-qa2.properties" 
      ignore-unresolvable="true" /> 

     <!-- scans for annotated classes in the com.env.test package --> 
     <context:component-scan base-package="com.glue.env.test" /> 
    </beans> 

    <beans profile="prod"> 
     <!-- allows for ${} replacement in the spring xml configuration from the 
      application-default.properties, application-prod files on the classpath --> 
     <context:property-placeholder 
      location="classpath:properties/application-web-default.properties, classpath:properties/application-web-prod.properties" 
      ignore-unresolvable="true" /> 

     <!-- scans for annotated classes in the com.env.prod package --> 
     <context:component-scan base-package="com.glue.env.prod" /> 
    </beans> 
    <beans profile="dev"> 
     <!-- allows for ${} replacement in the spring xml configuration from the 
      application-default.properties, application-dev files on the classpath --> 
     <context:property-placeholder 
      location="classpath:properties/application-api-default.properties, classpath:properties/application-api-dev.properties" 
      ignore-unresolvable="true" /> 

     <!-- scans for annotated classes in the com.env.dev package --> 
     <context:component-scan base-package="com.glue.env.dev" /> 
    </beans> 

    <beans profile="test"> 
     <!-- allows for ${} replacement in the spring xml configuration from the 
      application-default.properties, application-test files on the classpath --> 
     <context:property-placeholder 
      location="classpath:properties/application-api-default.properties, classpath:properties/application-api-qa2.properties" 
      ignore-unresolvable="true" /> 

     <!-- scans for annotated classes in the com.env.test package --> 
     <context:component-scan base-package="com.glue.env.test" /> 
    </beans> 

    <beans profile="prod"> 
     <!-- allows for ${} replacement in the spring xml configuration from the 
      application-default.properties, application-prod files on the classpath --> 
     <context:property-placeholder 
      location="classpath:properties/application-api-default.properties, classpath:properties/application-api-prod.properties" 
      ignore-unresolvable="true" /> 

     <!-- scans for annotated classes in the com.env.prod package --> 
     <context:component-scan base-package="com.glue.env.prod" /> 
    </beans> 

Спасибо заранее, пожалуйста, простите меня, если я сделал некоторые глупые ошибки, но Мне нужна ваша помощь.

+0

Какова цель 'GlueTestProperties'? –

+0

GlueTestProperties будет основным классом, он находится в разработке прямо сейчас, я просто проверял соединение до правильной реализации. – Shek

ответ

1

Если вы используете метод main, чтобы создать его, то весна ничего не узнает об этом классе, поэтому он не будет аутоуверить какие-либо классы - вы получите нули во всех полях, аннотированных @Autowired.

Ваш JUnit работает правильно, потому что он создан с помощью пружинного переключателя junit.

+0

Есть ли все-таки, чтобы это стало известно Spring? Должен ли я создавать bean-компоненты в моем xml? – Shek

+0

Это зависит от того, где вы его используете, проще всего сделать его компонентом и удалить статический метод. –

0

Я могу получить свойства для загрузки. Проблема заключалась в том, что, поскольку @krzyk указал, что мой класс реализации не был весенним, поэтому он не смог загрузить профиль из моего контекстного xml и чтобы он знал о моем профиле bean. Мне пришлось передать аргумент vm через мой основной класс, следуя коду изменение и подход помог мне:

мой класс реализации выглядеть это сейчас:

@ContextConfiguration("classpath:spring/xml-config-context.xml") 
public class GlueTestProperties { 


private GlueTestProperties() { 

    } 

    private static ApplicationContext context; 

    public static GenericEnv getEnv() { 
     return getContext().getBean(TestEnv.class); 
    } 

    public static WebPropertiesLoader getWebProperties() { 
     return getContext().getBean(WebPropertiesLoader.class); 
    } 

    public static ApiPropertiesLoader getApiProperties() { 
     return getContext().getBean(ApiPropertiesLoader.class); 
    } 

    private static ApplicationContext getContext() { 
     if (null == context) { 
      init(); 
     } 
     return context; 
    } 

    private static synchronized void init() { 
     context = new ClassPathXmlApplicationContext("spring/xml-config-context.xml"); 
    } 

} 

Я передаю следующее в качестве Vm аргумента: -Dspring.profiles.active=test

Или второй подход будет нужно вынуть

<context:property-placeholder 
      location="classpath:properties/application-web-default.properties, classpath:properties/application-web-qa2.properties" 
      ignore-unresolvable="true" /> 

от вашего <bean/> и поместите его в сторону, чтобы он был видимым для основного класса, и вам не нужно передавать аргументы vm здесь.

+0

Зачем ты добавил это в качестве ответа? Если он работает после прочтения моего ответа, то это не нужно. Если он все еще не работает, попробуйте комментарии/или отредактируйте свой вопрос. –

+0

Спасибо за вашу помощь @krzyk, вы действительно дали мне возможность начать, но это было гораздо больше, чем просто осознание весны, однако, чтобы поблагодарить вас, я поддерживаю ваш ответ. благодаря – Shek