欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PowerMock学习笔记(二) 博客分类: 单元测试  

程序员文章站 2024-02-14 20:41:04
...

PowerMock结合EasyMock

一、Mock静态方法
1、快速总结:
1)在测试用例类级使用@RunWith(PowerMockRunner.class)注释
2)在测试用例类级使用@PrepareForTest(ClassThatContainsStaticMethod.class)
3)使用PowerMock.mockStatic(ClassThatContainsStaticMethod.class)mock这个类的所有方法
4)使用PowerMock.replay(ClassThatContainsStaticMethod.class)切换至replay模式
5)使用PowerMock.verify(ClassThatContainsStaticMethod.class)切换至验证模式

2、例子
        假设存在如下类ServiceRegistrator:
public class ServiceRegistrator {
        public long registerService(Object service) {
                final long id = IdGenerator.generateNewId();
                serviceRegistrations.put(id, service);
                return id;
        }
}
        ServiceRegistrator引用了IdGenerator中的静态方法,为了测试registerService方法,我们需要mock IdGenerator.generateNewId()。
IdGenerator实现如下:
public class IdGenerator {

        /**
        * @return A new ID based on the current time.
        */
        public static long generateNewId() {
                  return System.currentTimeMillis();
        }

}

        要mock IdGenerator我们在类级使用@PrepareForTest(IdGenerator.class)来注释,并且告诉JUnit使用PowerMock:@RunWith(PowerMockRunner.class)
这两个注释是必须的,没有的话测试会失败。
package com.larry.junit;

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)

@PrepareForTest({IdGenerator.class})

public class ServiceRegistratorTest {

@Test

public void testRegistService() {

Long expectId = 12L;
ServiceRegistrator test = new ServiceRegistrator();
//mock
PowerMock.mockStatic(IdGenerator.class);
//expect
EasyMock.expect(IdGenerator.generateNewId()).andReturn(expectId);
//replay
PowerMock.replay(IdGenerator.class);
Long actualId = test.registerService(new Object());
//verify
PowerMock.verify(IdGenerator.class);
org.junit.Assert.assertEquals(expectId, actualId);

}

}