简体   繁体   中英

How to use @InjectMocks to inject dependency with same type?

I have a User class which has a constructor with two parameter of same type.

public class User {
    Dependency dependency1;
    Dependency dependency2;
    User(Dependency dependency1,Dependency dependency2){
        this.dependency1=dependency1;
        this.dependency2=dependency2;
    }
    public void test(){
        dependency1.print();
        dependency2.print();
    }
}

In my test, I have two Spy Dependency and I want them to be injected like new User(dependency1,dependency2) .

@ExtendWith(MockitoExtension.class)
public class InjectMocksTest {
    @InjectMocks
    User user;
    @Spy
    Dependency dependency1=new Dependency("dependent1");
    @Spy
    Dependency dependency2=new Dependency("dependent2");
    @Test
    void test(){
        user.test();
    }
}

But I find that dependency1 and dependency2 of User both refers to dependency1 in the test, like they are injected with new User(dependency1,dependency1) .

So how to achieve what I want with @InjectMocks annotation?

It appears that you can trick Mockito into injecting the mocks using Field injection if you create the object itself first, and set the arguments to null. This works for me:

@ExtendWith(MockitoExtension.class)
public class UserTest {
  @InjectMocks
  User user = new User(null, null);

  @Spy
  Dependency dependency1 = new Dependency("dependent1");
  @Spy
  Dependency dependency2 = new Dependency("dependent2");

  @Test
  void test() {
    user.test();
  }
}

Output:

dependent1
dependent2

However, this behavior is not documented, so I am not sure I would depend upon it.

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