如何在Mockito中模拟enum.values()

时间:2019-03-17 15:55:37

标签: java unit-testing mockito

首先,我正在学习Java和Mockito,进行了搜索,但尚未找到正确的答案。

伪代码是这样的

public enum ProdEnum {
    PROD1(1, "prod1"),
    PROD2(2, "prod2"),
    ......
    PROD99(2, "prod2");

    private final int id;
    private final String name;

    private ProdEnum(int id, String name) {
        this.id = id;
        this.name = name;
    }

    prublic String getName() { return this.name; }
}


public class enum1 {
   public static void main(String[] args) {
      // Prints "Hello, World" in the terminal window.
      System.out.println("Hello, World");

      List<String> prodNames = Array.stream(ProdEnum.values())
            .map(prodEnum::getName)
            .collect(Collectors.toList());

      // verify(prodNames);
   }
}

我的问题是在单元测试中,如何生成模拟的prodNames? 测试仅需要2或3种产品, 在我的单元测试中,我尝试过

List<ProdEnum> newProds = Arrays.asList(ProdEnum.PROD1, ProdEnum.PROD2);
when(ProdEnum.values()).thenReturn(newProds);

但是它说无法解析方法'thenReturn(java.util.List <... ProdEnum>)'

谢谢!

1 个答案:

答案 0 :(得分:1)

您无法在香草Mockito中模拟静力学。

如果您愿意进行一些重构,那么:

1):将404调用移至包级方法:

enum.values()

2)监视您的SUT:

.. List<String> prodNames = Array.stream(getProdNames()) .map(prodEnum::getName) .collect(Collectors.toList()); .. List<String> getProdNames(){ return ProdEnum.values(); }

3)模拟enum1 enumOneSpy = Mockito.spy(new enum1());方法:

getProdNames()
相关问题