简体   繁体   中英

How to Pass @Value to a @Component for Spring Unit Testing

Im writing unit tests for services, controllers, etc however theres is a @Component that has the following values

@Component
Public class myclass
   @Autowired
   Private MyTemplate myTemplate

   @Value("$someString")
   Private String someString

   @PostConstruct
   Public void loadString()
      ...

How would I manually load values into the @Values? I have tried with Mocks, TestPropertySource, ReflectionTestUtils, among other ways found around

I can immediately think of two options

1) You could define $someString in your test/resources/test.properties

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

  }

2) do it manually

@RunWith(SpringRunner.class)
public class ClassTest {

    @Autowired
     private MyClass miclass;

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

  }

You can inject the @Value in test class by ReflectionTestUtils. Load container only in case of Controllers. For writing test cases for services and dao you don't need to load the spring container.

public class TestClass{
 private @InjectsMock ServiceClass service; 

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

//your test cases over here.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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