How can I mock an instance of an enum class with PowerMock & Mockito?

前端 未结 3 438
无人及你
无人及你 2021-01-12 07:45

I tried to follow the example offered in the answer to this very similar question, but it does not work for me. I get the following error message:

java.lang.         


        
相关标签:
3条回答
  • 2021-01-12 08:08

    I got this working by extending the PowerMockTestCase class that handles this kind of thing for TestNG:

    @PrepareForTest(TestEnumerable.class)
    @Test(groups = {"LoadableBuilderTestGroup"})
    public class LoadableBuilderTest extends PowerMockTestCase {
    
     private TestEnumerable mockEnumerable;
    
     @SuppressWarnings("unchecked")
        @BeforeMethod
        public void setUp() {
            mockEnumerable = PowerMockito.mock(TestEnumerable.class);
    
        }
    }
    
    0 讨论(0)
  • 2021-01-12 08:11

    You need to run this with PowerMockRunner

    eg.

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ ExampleEnumerable.class})
    @Test(groups = {"LoadableBuilderTestGroup"})
    public class LoadableBuilderTest {
        private ExampleEnumerable mockEnumerable;
    
        @BeforeMethod
        public void setUp() {
            mockEnumerable = mock(ExampleEnumerable.class);
        }
    }
    
    0 讨论(0)
  • 2021-01-12 08:12

    Hi guys, to me worked as below:

    First add power mockito on pom.xml:

    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.4</version>
        <scope>test</scope>
    </dependency>
    

    and then on my class:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({EnumClass.class})
    public class EnumClassTest{
        private EnumClassTest enumClassTest;
        
        @Before
        public void setUp() {
            enumClassTest = mock(EnumClassTest.class);
        }
        
        @Test
        public void someMethod() {
            //My code test here
        }  
    
    0 讨论(0)
提交回复
热议问题