简体   繁体   中英

Spring inject resource used by static method

I have a Unit test set up as follows:

  1. Unit Test using Mockito runs and creates an Object (class is not using Spring)
  2. Object calls a static method in a utility class (Spring Component) called TimeUtil during its construction
  3. TimeUtil has a field called TimeService (static Spring Component) that fetches the time

Workflow: Unit Test -> Create Object -> Static method call in TimeUtil -> Fetch time from TimeService

This workflow works fine in production however it has been challenging to test, for some reason the TimeService in TimeUtil is always null. Spring is supposed to inject an instance of TimeService into TimeUtil at runtime.

Can anyone advise on why my TimeService keeps coming back as null?

I tried using Mockito to capture the static method call but this didn't work, similarly I can't inject a TimeService mock into the object class since this statically calls TimeUtil.

You need to look through the Spring configuration to find out how you (or someone from your team) made Spring wire up the static TimeService . Normally, Spring only works on beans which it created. So global variables and static methods are not supported. Someone must have written code to make the injection happen in this case.

Show us this code and we can help you improve it to allow for unit tests.

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