powermock单元测试小结
最近时不时的需要单元测试来写覆盖率。简单总结一下日常心得:
1.首先指明需要测试的类:@PrepareForTest({ RewardGoldServiceImpl.class })
2.其次在测试类中new出被测试对象:@InjectMocks
RewardGoldServiceImpl rewardGoldService = new RewardGoldServiceImpl();
3.然后在遇到所需测试类中的dao方法时候,进行mock:@Mock
IDictionaryDao dictionaryDao;
进行预加载类:@Before
public void init() {
MockitoAnnotations.initMocks(this);
}
4.最后编写测试类进行测试,主体代码如下:
@PrepareForTest({ RewardGoldServiceImpl.class }) public class RewardGoldServiceImplTest { // 被测对象 @InjectMocks RewardGoldServiceImpl rewardGoldService = new RewardGoldServiceImpl(); /** * 字典表操作 */ @Mock IDictionaryDao dictionaryDao; @Mock IRewardGoldDao rewardGoldDao; @Before public void init() { MockitoAnnotations.initMocks(this); } @Test public void testGetSystemMoney(){ String accountPeriod = "201812"; String payMerchantCode = "7236402"; List<DictionaryPo> dictionaryList = new ArrayList<DictionaryPo>(); DictionaryPo dictionaryPo = new DictionaryPo(); PowerMockito.when(dictionaryDao.getDictionaryByFieldName("freightBonusProductCode")).thenReturn(dictionaryList); dictionaryPo.setFieldID(1); dictionaryPo.setFieldName("111"); dictionaryPo.setFieldValue("123"); dictionaryList.add(dictionaryPo); rewardGoldService.getSystemMoney(accountPeriod, payMerchantCode); } }