Mocking Java enum to add a value to test fail case

前端 未结 10 1448
死守一世寂寞
死守一世寂寞 2020-11-28 23:55

I have an enum switch more or less like this:

public static enum MyEnum {A, B}

public int foo(MyEnum value) {
    switch(value) {
        case(A):          


        
10条回答
  •  天命终不由人
    2020-11-29 00:52

    Here is a complete example.

    The code is almost like your original (just simplified better test validation):

    public enum MyEnum {A, B}
    
    public class Bar {
    
        public int foo(MyEnum value) {
            switch (value) {
                case A: return 1;
                case B: return 2;
            }
            throw new IllegalArgumentException("Do not know how to handle " + value);
        }
    }
    

    And here is the unit test with full code coverage, the test works with Powermock (1.4.10), Mockito (1.8.5) and JUnit (4.8.2):

    @RunWith(PowerMockRunner.class)
    public class BarTest {
    
        private Bar bar;
    
        @Before
        public void createBar() {
            bar = new Bar();
        }
    
        @Test(expected = IllegalArgumentException.class)
        @PrepareForTest(MyEnum.class)
        public void unknownValueShouldThrowException() throws Exception {
            MyEnum C = mock(MyEnum.class);
            when(C.ordinal()).thenReturn(2);
    
            PowerMockito.mockStatic(MyEnum.class);
            PowerMockito.when(MyEnum.values()).thenReturn(new MyEnum[]{MyEnum.A, MyEnum.B, C});
    
            bar.foo(C);
        }
    
        @Test
        public void AShouldReturn1() {
            assertEquals(1, bar.foo(MyEnum.A));
        }
    
        @Test
        public void BShouldReturn2() {
            assertEquals(2, bar.foo(MyEnum.B));
        }
    }
    

    Result:

    Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.628 sec
    

提交回复
热议问题