如何在Spring中使用autowire for Set时模拟实现相同接口的所有类?

时间:2016-12-04 11:19:13

标签: java spring mocking mockito junit4

拥有以下课程:

public class A {
     @Autowired
     private Set<IClient> clients;  
 }

public class B implements IClient { }

public class C implements IClient { }


@RunWith(MockitoJUnitRunner.class)
public class Atest {
    @InjectMocks
    A a;

    @Mock
    IClient clients;
}

如何将mocks用于包含Set类和B类的C接口?

1 个答案:

答案 0 :(得分:2)

使用构造函数注入字段注入,然后创建两个模拟,将它们放在一个集合中,并使用该集合调用构造函数。例如:

public class Atest {
    private A a;

    @Mock
    private IClient mockAClient;

    @Mock
    private IClient mockBClient;

    @Before
    public void prepare() {
        a = new A(new HashSet<>(Arrays.asList(mockAClient, mockBClient));
    }

}