【问题标题】:How to set and inject property Value from Test in Junit如何在 Junit 中从测试中设置和注入属性值
【发布时间】:2019-09-26 00:26:00
【问题描述】:

我的服务类使用一个属性设置它 application.properties

@Service
public class Service {
    @Value("${my.prop}")
    private String prop;        
    public Response doWork(String param1,String param2){
       System.out.println(prop);    //NULL!!! 
    }   
}

我想测试它并设置我自己的值:

测试类:

@RunWith(MockitoJUnitRunner.class)
@TestPropertySource(locations = "application.properties",properties = { "my.prop=boo" })
public class ServiceUnitTest {   
    @InjectMocks
    private Service service;    

    @Test
    public void fooTest(){      
        Response re = service.doWork("boo", "foo");
    }
}

但是当我运行测试时,该值为 null(甚至不是 application.properties 中存在的值)。

【问题讨论】:

  • 使用构造函数注入而不是字段注入。然后使用new Service("whatever") 创建您的服务实例。

标签: spring junit


【解决方案1】:

我没有使用 MockitoJUnitRunner 的经验,但我可以使用 PowerMockRunner 来实现。

使用测试配置设置应用程序上下文,并将 bean 从您的应用程序上下文自动装配到您的测试类中。您也不应该需要 @TestPropertySource 注释中的“locations =”位。

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@TestPropertySource(properties = { "my.prop=boo" })
public class ServiceUnitTest {   

    @TestConfiguration
    static class ServiceUnitTestConfig {
        @Bean
        public Service service() {
            return new Service();
        }
    }

    @Autowired
    Service service;

    @Test
    public void fooTest(){      
        Response re = service.doWork("boo", "foo");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    • 2011-09-26
    • 1970-01-01
    • 2010-09-19
    • 2013-07-21
    • 1970-01-01
    • 2019-04-26
    相关资源
    最近更新 更多