Junit测试对象保存和读取方法

时间:2013-07-28 21:27:47

标签: java junit

我需要有关单元测试对象的保存和读取方法的最佳方法的帮助。这是简单的Object,这里是构造函数:

public Bill(String bname, Double bamount, Date bdate, String bfrequency){
    this.billName = bname;
    this.billAmount = bamount;
    this.billDueDate = bdate;
    this.frequency = bfrequency;

}

我实现了一个接口,它将定义一个读取和保存方法,如此

public interface IBill {
    public void save(Bill bill) throws IOException;
    public Bill read() throws IOException;

请耐心等待,这是上述界面的具体实现

public class BillSvcImpl implements IBill {

    @Override
    public void save(Bill bill) throws IOException {
        FileOutputStream fOut = null;
        ObjectOutputStream oOut = null;

        try {
            fOut = new FileOutputStream("firstbill.ser");           
            oOut = new ObjectOutputStream(fOut);
            oOut.writeObject(bill);   //serializing Bill object

        } catch (IOException e) {
            e.printStackTrace();

            try{
                oOut.flush();
                oOut.close();
                fOut.close();
            }catch (IOException ioe){
                        ioe.printStackTrace();
            }
        }
    }



    @Override
    public Bill read() {

        Bill retrievedBill = null;
        FileInputStream fIn = null;
        ObjectInputStream oIn = null;

        try{
            fIn = new FileInputStream("firstbill.ser");         
            oIn = new ObjectInputStream(fIn);           
            retrievedBill = (Bill)oIn.readObject();

        }catch (ClassNotFoundException cnf){
                    cnf.printStackTrace();
        }catch (IOException e){
            try{
                oIn.close();
                fIn.close();
            }catch (IOException ioe){
                ioe.printStackTrace();
            }
        }
        return retrievedBill;
    }

    }

最后这里是我想用来测试这个方法的测试,它失败了

@Before
public void setUp() throws Exception {
    factory = new Factory();

}
@test
public void testSaveBill(){
    IBill bill = factory.getBillInfo();
    Bill nanny = new Bill("Nanny",128d,new Date(6/28/2013),"Montly");
    try {
        bill.save(nanny);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 @test
 public void testReadBill(){
     IBill rbill = factory.getBillInfo();
     try {
        rbill.read();
    } catch (IOException e) {
        e.printStackTrace();
    }

 }

}

我知道我的测试不对,所以请帮我重新编写测试。错误消息为Java.lang.Exception: No runnable method

1 个答案:

答案 0 :(得分:0)

如果您使用JUnit 4.x,那么您需要使用@Test注释标记您的方法(案例事项)3.x测试类必须extends TestCase才能使您的测试工作。

如果您设计单元测试,则不必实际序列化对象,然后对其进行反序列化。我会使用FileInputStream fIn方法将ObjectInputStream oInget/set移动到类级属性并将其模拟为测试(很少有好的模拟框架实现12