使用@Spy和@InjectMocks模拟多个Vector <string>

时间:2018-04-16 19:10:08

标签: spring junit dependency-injection mockito spy

我正在编写一个JUnit测试,我需要按如下方式注入2个向量的模拟:

@AllArgsConstructor
public abstract class AbstractMyObject {  
    @Autowired
    private Vector<String> firstVector;

    @Autowired
    private Vector<String> secondVector;

    public abstract void  absFunc();

    public void doThis() {
        System.out.println(firstVector);
        System.out.println(secondVector);
    }
}

@Component
public class MyObject extends AbstractMyObject {
    public MyObject(final Vector<String> firstVector, final Vector<String> secondVector) {
        super(firstVector, secondVector);
    }
    @Override
    public void absFunc() {

    }
}

public class TestClass {
    private static String[] array1 = {"Hello", "World"};
    private static String[] array2 = {"junit", "mockito"};

    @Spy
    private Vector<String> firstVector = new Vector<>(Arrays.asList(array1));

    @Spy
    private Vector<String> secondVector = new Vector<>(Arrays.asList(array2));

    @InjectMocks
    private MyObject myObject;

    private void initMocks() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test1() {
        initMocks();
        myObject.doThis();
    }
}

运行此测试的输出是:[Hello,World]

如何确保两个向量都已正确分配?

我找不到任何关于在Spy和InjectMocks中使用@Qualifier的示例或文档。

1 个答案:

答案 0 :(得分:1)

我从基类调用super()是不正确的。由于成员是@Autowire-d,因此不需要super()。