这是需要测试的类,其中只有两个简单的方法,set与get
package Bug;
public class Report {
    protected int ProductId;
    public Report() {
    }
    public void setProductId(int ProductId){
        this.ProductId=ProductId;
    }
    public int getProductId(){
        return this.ProductId;
    }
}
这是本人对Report类的测试代码
package Bug;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ReportTest extends TestCase {
private Report a; protected void setUp() throws Exception {
super.setUp();
if (a == null) {
a = new Report();
} } /*
 * @see TestCase#tearDown()
 */
protected void tearDown() throws Exception {
super.tearDown();
a = null;
} public static TestSuite suite() {
return new TestSuite(ReportTest.class);
} public static void main(String[] args) {
junit.swingui.TestRunner.run(ReportTest.class);
}
public void testSetProductId() { int ProductId = 2; a.setProductId(ProductId);
} public void testGetProductId() {
int expResult = 2;
int result = a.getProductId();
assertEquals(expResult, result);
}}碰到的问题是我无法在get方法测试中取得我在上面测试set方法时的值,在testGetProuductId方法中的result值总是0,不知道是为什么,set方法已经测试成功,谢谢大虾们指点

解决方案 »

  1.   

    这个代码是你手工写的还是生成的?看样子应该是先调用了testGetProductId,此时,从a取到的expResult是0,当然出错了。
    至于set因为没有返回值,所以一直是正确的。
      

  2.   

    我认为:junit执行的顺序是
    setUp
    testSetProductId
    tearDown
    setUp
    testGetProductId
    tearDown因此在testGetProductId中a.getProductId()取得的是默认值0
    可以这样写测试点:
    public void testSetProductId() {
        int ProductId = 2;
        a.setProductId(ProductId);
        assertTrue(a.ProductId,2);}