简体   繁体   English

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

[英]How to mock enum.values() in mockito

First of all i'm learning java and mockito, did search and cannot find proper answer yet. 首先,我正在学习Java和Mockito,进行了搜索并且找不到合适的答案。

The pseudo code is like this 伪代码是这样的

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);
   }
}

My question is in unit test, how to generate mocked prodNames ? 我的问题是在单元测试中,如何生成模拟的prodNames? Only 2 or 3 of the products needed for testing, In my unit test i tried this 仅2或3种产品需要测试,在我的单元测试中,我尝试了

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

but it says Cannot resolve method 'thenReturn(java.util.List<...ProdEnum>)' 但是它说无法解析方法'thenReturn(java.util.List <... ProdEnum>)'

Thanks ! 谢谢 !

You cannot mock statics in vanilla Mockito. 您无法在香草Mockito中模拟静力学。

If your up for a little refactor then: 如果您需要一点重构,那么:

1) Move enum.values() call into a package level method: 1)enum.values()调用移至包级方法中:

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

List<String> getProdNames(){
  return ProdEnum.values();
}

2) Spy on your SUT: 2)监视您的SUT:

enum1 enumOneSpy = Mockito.spy(new enum1());

3) Mock the getProdNames() method: 3)模拟getProdNames()方法:

doReturn(newProds).when(enumOneSpy).getProdNames();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM