简体   繁体   中英

Mockito InjectMocks into static object

I have something like this

@Component
public class TestController {

    @Autowired
    private TestService testService;

    public String getSomething(String parameter1) {
        return testService.fetchSomething(parameter1);
    }
}

And I am covering it with tests and have the following problem:

@RunWith(MockitoJUnitRunner.class)
public class TestControllerTest {
    private static TestService testService = mock(TestService.class);
    @InjectMocks
    private static TestController testController = new TestController();

    ....
}

These fields are static because I need them for @ClassRule.

The problem is that in this case injection doesn't work, and testService is null in testController.

Is it possible to provide injection into static object (without constructor creation in Controller)? Or maybe there is another workaround for this?

The question is not about mocking static methods, but injecting mocks into static objects Will appreciate any advice, thanks.

I think you would have to use a static block.

@RunWith(MockitoJUnitRunner.class)
public class TestControllerTest {
    private static TestService testService = mock(TestService.class);

    private static TestController testController ;
    static {
       testController = new TestController(testService);
    }
    ....
}

As you use magically injection you have have to use some reflection, or change to constructor injection. Life is better that way anyway.

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