代码之家  ›  专栏  ›  技术社区  ›  Deepboy

@testpropertySource-未将测试属性文件中的值设置为空

  •  0
  • Deepboy  · 技术社区  · 6 年前

    我的JUnit没有获取在测试属性文件中设置的属性。 我没有得到错误,但从属性文件返回的值为空

    试验等级:

    package com.abc.mysource.mypackage;
    
    @Component
    @ComponentScan
    public class MyHelper {
    
        @Autowired
        @Qualifier("commonProperties")
        private CommonProperties commonProperties;  
    
        public LocalDateTime method1ThatUsesCommonProperties(LocalDateTime startDateTime) throws Exception {
            String customUserType = commonProperties.getUserType(); // Returns null if run as JUnit test
            //Further processing
        }
    }
    

    支持组件-bean和config类:

    package com.abc.mysource.mypackage;
    @Component
    public class CommonProperties {
         @Value("${myhelper.userType}")
         private String userType;
    
             public String getUserType() {
            return userType;
        }
        public void setCalendarType(String userType) {
            this.userType = userType;
        }
    }
    

    配置类:

    package com.abc.mysource.mypackage;
    @Configuration
    @ComponentScan(basePackages ="com.abc.mysource.mypackage.*")
    @PropertySource("classpath:default.properties")
    public class CommonConfig {}
    

    src/main/resources下的default.properties

    myhelper.userType=PRIORITY
    

    我的测试课:

    package com.abc.mysource.mypackage.test;
    @RunWith(SpringRunner.class)
    @ContextConfiguration(classes=MyHelper.class)
    @TestPropertySource("classpath:default-test.properties")
    @EnableConfigurationProperties
    public class MyHelperTest {
        @MockBean(name="commonProperties")
        private CommonProperties commonProperties;
    
        @Autowired
        private MyHelper myHelper;
    
        @Test
        public void testMethod1ThatUsesCommonProperties() {
            myHelper.method1ThatUsesCommonProperties();
        }
    }
    

    在/src/test/resources下定义的default-test.properties:

    myhelper.userType=COMMON
    

    注:

    我将default-test.properties移动到/src/main/resources-commonproperties.getUserType()为空

    我甚至使用了@testpropertySource(properties=“myHelper.userType=common”)。同样结果

    注2:

    我试过这个方法 @TestPropertySource is not loading properties .

    这个解决方案需要我在SRC/Test/Java下创建一个称为通用属性的重复bean。但是@mockbean失败了

    @MockBean(name="commonProperties")
    private CommonProperties commonProperties;
    

    请不要标记副本。

    注3: 我的是弹簧,不是弹簧引导应用程序。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Adina Rolea    6 年前

    如果您不需要特定的状态,mockbean是合适的。通常这个bean是“隔离的”,并且这个bean的每个方法调用都会有相同的结果。它是“隔离的”->使用@value注释的服务将不会应用于此bean。

    您需要的是一个“普通”bean,正确构造和初始化。如果需要,请使用@autowired annotation并使用测试配置文件定义另一个bean。