0

First of all i'm learning java and mockito, did search and cannot find proper answer yet.

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 ? Only 2 or 3 of the products needed for testing, In my unit test i tried this

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>)'

Thanks !

5
  • 4
    Why would you mock an Enum? Commented Mar 17, 2019 at 15:58
  • @LppEdd i'm learning, my goal is to get mocked prodNames, but don't know how to do it Commented Mar 17, 2019 at 16:04
  • You would usually have a SUT (Subject Under Test) class and inject the mocked dependencies, then verify the SUT behaviour from the interactions with the mocked dependencies. There is no value or point in doing this with an enum - are you trying to verify enums or streams work? Commented Mar 17, 2019 at 16:05
  • You can only call thenReturn on a mock. Did you instantiate the mock? Commented Mar 17, 2019 at 16:22
  • @Kars yes i do have mock, the above is just pseudo code. Commented Mar 17, 2019 at 16:26

1 Answer 1

2

You cannot mock statics in vanilla Mockito.

If your up for a little refactor then:

1) Move enum.values() call into a package level method:

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

2) Spy on your SUT:

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

3) Mock the getProdNames() method:

doReturn(newProds).when(enumOneSpy).getProdNames(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Good to know that, in the end i just want to mock some string values for prodNames, is there a simpler way to bypass adding getProdNames() ?
you would need to use PowerMockito. That enables static method mocking

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.