Cannot run powermockrule with SpringJUnit4ClassRunner in spring boot project

前端 未结 2 1481
半阙折子戏
半阙折子戏 2020-12-11 07:53

I have a spring boot project that needs to test with spring test runner(so that I can get the real application context) and mock the static method.

@RunWith(         


        
相关标签:
2条回答
  • 2020-12-11 08:39

    Spring, camel & powermock unittest:

    I had also same problem with PowerMockRule. I replaced it with following annotations

    @RunWith(PowerMockRunner.class)
    @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
    

    .

    Also remove dependencies powermock-module-junit4-rule & powermock-classloading-xstream from Pom.xml and it works.

     @RunWith(PowerMockRunner.class)
        @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
        @ContextConfiguration(classes = { StaticClassTest.ContextConfig.class })    
        @PrepareForTest({ StaticClass.class })
        @PowerMockIgnore("javax.management.*")
        public class StaticClassTest extends DroolsHelper {
    
         @Before
        public void setup() {
            PowerMockito.mockStatic(StaticClass.class);
    
        }
    
            @Produce(uri = "direct:start")
            private ProducerTemplate template;
    
            /**
             * 
             * ContextConfig.
             */
            @Configuration
            @Import(AppConfig.class)
            public static class ContextConfig extends SingleRouteCamelConfiguration 
             {
    
                @Bean
                @Override
                public RouteBuilder route() {
                    return new RouteBuilder() {
                        @Override
                        public void configure() {
                            from("direct:start").to("kie:kieSessionType?action=insertBody");
                        }
                    };
                }
    
            }
     @Test
        public void test() {
    
    
            PowerMockito.when(StaticClass.anyMethod(Matchers.any(TestClass.class)).thenReturn(false);
            ......assert.........
        }
        }
    
    0 讨论(0)
  • 2020-12-11 08:47

    I found a fix from here link to use PowerMockRunnerDelegate instead of PowerMockRule.

    The updated test class would be:

    @RunWith(PowerMockRunner.class)
    @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes= MyApplication.class)
    @PrepareForTest(StaticClass.class)
    public class StaticClassTest {
    
        @Autowired
        HelloCmd hello;
    
        @Test
        public void testGetOne() {
            mockStatic(StaticClass.class);
            when(StaticClass.getNumber()).thenReturn(2);
            System.out.println(hello.getNumber());
        }
    }
    
    0 讨论(0)
提交回复
热议问题