JUnit, Spring (SpringJUnit4ClassRunner) и проводка Spring не работают должным образом (пробовали запустить из Eclipse и командной строки Maven)?

Я столкнулся с проблемой, когда bean-компонент, который я пытаюсь подключить через конфигурацию spring, не работает? Средство доступа к bean-компоненту отображается как null во время проверки в моем тестовом примере (но я наблюдаю в журналах, что установщик фактически устанавливает для него допустимое значение. Может действительно пригодиться некоторая помощь...

Вот код:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="/test-context.xml")
public abstract class HistoryCompress extends TestBase {

    private CompressionArchive compressArchive;
    public void setCompressionArchive(CompressionArchive value)
    {
        this.logInfo("setting compression archive: %s, name: %s",value,value.getcompressionFormat());
        this.compressArchive=value;
    }

    protected CompressionArchive getCompressionArchive()
    {
        return this.compressArchive;
    }

    @Test
    public void getArchiveTypeName()
    {
        logInfo("test");
        this.assertNotNull(this.getCompressionArchive(),"compression archive is null");     
        this.assertNotNull(this.getCompressionArchive().getcompressionFormat(), "format name is null");
        logInfo("format: %s",this.getCompressionArchive().getcompressionFormat());
    }

}

public class HistoryZipCompress extends HistoryCompress 
{
    public HistoryZipCompress()
    {
        this.logInfo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        this.logInfo("-=-=-=--=- C'Tor HistoryZipCompress");
        this.logInfo("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
    }

}

public interface CompressionArchive {
    public String getcompressionFormat();
    public Map<String,String> getArchiveHashes(InputStream stream,String password) throws Exception;
}
public class CompressionArchiveZip extends IntegrationBase implements CompressionArchive
{
   /* implementation methods*/
}


И затем я пытаюсь связать это со следующей конфигурацией

<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"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:util="http://www.springframework.org/schema/util" 
    default-autowire="byName"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <context:annotation-config />       
    <bean class="gdg.scc.integration.testcases.file.history.HistoryZipCompress">
        <property name="compressionArchive"  ref="zipArchive" />
    </bean>     
    <bean id="zipArchive" class="gdg.scc.integration.global.helpers.compression.impl.CompressionArchiveZip" />
</beans>

Когда я запускаю это, я наблюдаю, что экземпляр HistoryZipCompress создается 3 раза, вот хвост из запуска getArchiveTypeName на HistoryZipCompress:

16-Jan 13:21:09 - INFO  - main - org.springframework.context.support.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext@2bfe605c: startup date [Wed Jan 16 13:21:09 MST 2013]; root of context hierarchy
16-Jan 13:21:09 - INFO  - main - org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
16-Jan 13:21:09 - INFO  - main - org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@578bb31a: defining beans [fileSystemAPIUrl,defaultShopperAccount,shopperAccounts,orionAccountCredential,SCC.FileTypeMappings.js,fileTypeGenerator,regexToExtensionMap,activeMQMessageProperties,automatorServiceInfo,activeMQAutomtorPublisher,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,logResultsToAutomator,orionAccountHelper,gdg.scc.integration.testcases.file.history.HistoryZipCompress#0,zipArchive,extensionToMimeType]; root of factory hierarchy
16-Jan 13:21:09 - INFO  - main - integration.testcases.file.history.HistoryZipCompress - -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
16-Jan 13:21:09 - INFO  - main - integration.testcases.file.history.HistoryZipCompress - -=-=-=--=- C'Tor HistoryZipCompress
16-Jan 13:21:09 - INFO  - main - integration.testcases.file.history.HistoryZipCompress - -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
16-Jan 13:21:09 - INFO  - main - integration.testcases.file.history.HistoryZipCompress - setting compression archive: integration.global.helpers.compression.impl.CompressionArchiveZip@6a367507, name: zip
16-Jan 13:21:09 - INFO  - main - integration.testcases.file.history.HistoryZipCompress - test
16-Jan 13:21:09 - INFO  - Thread-0 - org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@2bfe605c: startup date [Wed Jan 16 13:21:09 MST 2013]; root of context hierarchy
16-Jan 13:21:09 - INFO  - Thread-0 - org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@578bb31a: defining beans [fileSystemAPIUrl,fileTypeGenerator,regexToExtensionMap,activeMQMessageProperties,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,integration.testcases.file.history.HistoryZipCompress#0,zipArchive,extensionToMimeType]; root of factory hierarchy

person Arthur Strutzenberg    schedule 16.01.2013    source источник
comment
Я могу выполнить тест, он запускается и загружает тестовый пример, однако, когда тестовый пример достигает строки this.assertNotNull(this.getCompressionArchive(), архив сжатия равен нулю); это не удается, потому что getCompressionArchive возвращает значение null   -  person Arthur Strutzenberg    schedule 17.01.2013
comment
Вы пробовали @Autowired, как я предложил? Это действительно должно работать :)   -  person theadam    schedule 17.01.2013


Ответы (1)


Аннотируйте поле с помощью @Autowired:

@Autowired
private CompressionArchive compressArchive;

Выкинь HistoryZipCompress в конфиге xml - что он там делает? Вам не нужно создавать еще один экземпляр тестового класса, бегун сделает это за вас.

Вам нужно, чтобы ваш тестовый объект был внедрен с экземпляром CompressionArchive. Spring runner управляет вашим тестовым объектом (HistoryCompress), но не знает, хотите ли вы ввести экземпляр CompressionArchive.

person theadam    schedule 16.01.2013