繁体   English   中英

如何将@Value传递给@Component进行弹簧单元测试

[英]How to Pass @Value to a @Component for Spring Unit Testing

我正在为服务,控制器等编写单元测试,但是这里有一个@Component,其值如下

@Component
Public class myclass
   @Autowired
   Private MyTemplate myTemplate

   @Value("$someString")
   Private String someString

   @PostConstruct
   Public void loadString()
      ...

我将如何手动将值加载到@Values中? 我尝试过Mocks,TestPropertySource,ReflectionTestUtils等

我可以立即想到两个选择

1)您可以在test / resources / test.properties中定义$ someString

@RunWith(SpringRunner.class)
@TestPropertySource(locations="classpath:test.properties")
public class ClassTest {

  }

2)手动执行

@RunWith(SpringRunner.class)
public class ClassTest {

    @Autowired
     private MyClass miclass;

 @Before
 public void setupObject() {
     miclass.setProperty("someting");
  }

  }

您可以通过ReflectionTestUtils在测试类中注入@Value。 仅在控制器的情况下加载容器。 为了编写服务和dao的测试用例,您不需要加载spring容器。

public class TestClass{
 private @InjectsMock ServiceClass service; 

 @BeforeAll
 public void setUp(){
    ReflectionTestUtils.setField(service, "someString", "someValue");
 }

//your test cases over here.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM