java如何测试静态方法,如何在Java中模拟静态方法?

I have a class FileGenerator, and I'm writing a test for the generateFile() method that should do the following:

1) it should call the static method getBlockImpl(FileTypeEnum) on BlockAbstractFactory

2) it should populate variable blockList from the subclass method getBlocks()

3) it should call a static method createFile from a final helper class FileHelper passing a String parameter

4) it should call the run method of each BlockController in the blockList

So far, I have this empty method:

public class FileGenerator {

// private fields with Getters and Setters

public void generateBlocks() {

}

}

I am using JUnit, Mockito to mock objects and I've tried using PowerMockito to mock static and final classes (which Mockito doesn't do).

My problem is: my first test (calling method getBlockList() from BlockAbstractFactory) is passing, even though there is no implementation in generateBlocks(). I have implemented the static method in BlockAbstractFactory (returning null, so far), to avoid Eclipse syntax errors.

How can I test if the static method is called within fileGerator.generateBlocks()?

Here's my Test Class, so far:

@RunWith(PowerMockRunner.class)

public class testFileGenerator {

FileGenerator fileGenerator = new FileGenerator();

@Test

public void shouldCallGetBlockList() {

fileGenerator.setFileType(FileTypeEnum.SPED_FISCAL);

fileGenerator.generateBlocks();

PowerMockito.mockStatic(BlockAbstractFactory.class);

PowerMockito.verifyStatic();

BlockAbstractFactory.getBlockImpl(fileGenerator.getFileType());

}

}

解决方案

I have no experience with PowerMock, but since you didn't get an answer yet I'm just been reading through the documentation to see if I can help you a bit on your way.

I found that you need to prepare PowerMock so that I knows which static methods it needs to prepare to be mocked. Like so:

@RunWith(PowerMockRunner.class)

@PrepareForTest(BlockAbstractFactory.class) // <<=== Like that

public class testFileGenerator {

// rest of you class

}

Here you can find more information.

Does that help?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值