简体   繁体   中英

How to test dependency injection with annotations?

In Spring Framework or Java EE there are annotation based Dependency Injection.

Normally you would do

class X
{
    Y var;

    public X(Y var)
    {
       this.var = var
    }
}

This is so easy to test and mock. You just instantiate class Y as you like for your test.

But how about this.

class X
{
    @Inject or @Autowired
    Y var;

    public X( )
    {

    }
}

How about annotation based Dependency Injection. You have the same problem as with hard coded instatiation. I have no possiblity to inject a mocked object as I could in the first code example. How can I test it?

I have no possiblity to inject a mocked object as I could in the first code example

Why is that?

@Component
class X {
    Y var;

    @Autowired
    public X(Y var)
    {
       this.var = var
    }


   @Component
   class Y {
  
   }

And then

@RunWith(SpringRunner.class)
public class ApiControllerTest {
 
    @Autowired
    private X x;
 
    @Configuration
    static class Config {
 
        @MockBean
        private Y y;
    }
}

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