PowerMock使用

最近写UT时使用easymock发现不能满足对于static的mock,最终发现了powermock,用了下很爽。

 

坐标

<dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito</artifactId>
            <version>${powermock.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>

目前使用的PoerMock版本是:

<powermock.version>1.5.4</powermock.version>

 

常规使用方式@RunWith(PowerMockRunner.class)

@PrepareForTest( {WebPageNoticePublisher.class, AppService.class})
public class ApplicationDeployerTest {
    @Test
    public void test_appInstanceIsNull() throws Exception {
        String resourceId = "";
        Long actorId = 1L;
        RequestImpl request = new ResponseImpl();

        /**
         * 使用mockStatic为要mock的静态方法做准备
         */
        mockStatic(WebPageNoticePublisher.class);
//这里mock void的static method doNothing().when(WebPageNoticePublisher.
class, "notice", anyString(), any(Notice.class));      //invoke method ApplicationDeployerImpl applicationDeployer = new ApplicationDeployerImpl(false); applicationDeployer.handle(resourceId, actorId, request); //验证static方法被调用了一次 verifyStatic(times(1));
     //实际调用 WebPageNoticePublisher.notice(anyString(), any(Notice.
class)); } }

 

posted @ 2014-04-16 11:45  小玄子的后花园  阅读(852)  评论(0编辑  收藏  举报