写java程序如何测试,如何测试写入Java文件?

I'm beginner, and keep yourself in hands.

I have some easy program, and I need do junit test for write method. I have some collection in input. How I can do this? This my code:

// write to file

public void write(String fileName,

List figuresList) {

try {

PrintWriter out = new PrintWriter(

new File(fileName).getAbsoluteFile());

try {

for (int i = 0; i < figuresList.size(); i++) {

out.println(figuresList.get(i).toString());

}

} finally {

out.close();

}

} catch (IOException e) {

System.out.println("Cannot write to file!");

}

}

And I want to know, coz after this I read from file, can we join both tests(write/read) or better do this individually(coz if our test fall we don't know where is problem - in read or write)? How should make this correctly at junit(with prepare to test, and test itself)?

Better show on example, this way better to understand.

Thanks, Nazar.

解决方案

I'll suggest you making an interface wrapper around you IO classes (the PrintWriter class in your case) so you can use mock objects for output. You don't have to test Java PrintWriter, you want to test your functionality, right?

So your class will be

class MyClass {

MyWriter out;

public void setOut(MyWriter out) {

this.out = out;

}

// write to file

public void write(String fileName, List figuresList) {

try {

try {

for (int i = 0; i < figuresList.size(); i++) {

out.println(figuresList.get(i).toString());

}

} finally {

out.close();

}

} catch (IOException e) {

System.out.println("Cannot write to file!");

}

}

}

The signature of the MyWriter interface is pretty straightforward.

interface MyWriter {

void println(Object x); // You can add other println methods here.

void close();

}

Then you can use EasyMock to write a test. The test method will be something like

@Test

public void testWrite() {

MyWriter out = EasyMock.createMock(MyWriter.class);

EasyMock.expect(mock.println(EasyMock.anyObject())).times(3);

EasyMock.expect(mock.close()).times(1);

List list = ...

list.add(...);

list.add(...);

list.add(...);

replay(mock);

MyClass myClass = new MyClass();

myClass.setOut(out);

myClass.write("mockFileName", list);

verify(mock);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值