0

我有一个非常小的类BuildThreeObjects ,它使用私有 int 变量numObjects创建最多 3 个对象来存储计数。如果计数 < 3,则返回一个新对象,否则null返回。

谁能指导我如何测试是否使用 JUnit 创建了最多 3 个对象。查看 API 并没有太大帮助。我假设assertNotNullassertNull将被使用,但我想不出怎么做。


// BuildThreeObjects 类的代码

public class BuildThreeObjects {
    private int numObjects = 0;

    public Object buildObject() {
        if (numObjects<3) {
                numObjects++;
            return new Object();
        }
        else return null;
    }
}

// JUnit 类中的代码;省略所有不必要的代码

private BuildThreeObjects bto;

@Before
public void setUp() throws Exception {
    bto = new BuildThreeObjects();
}

@Test
public void testBuild() {
    assertNotNull(bto.buildObject());
}

// assertNotNull passes and assertNull fails as it only checks the first object creation
4

2 回答 2

2

你的意思是这样的?

class BuildThreeObjects{
    int count = 0;
    public Object buildObject(){
        if(count >= 3){
            return null;
        } else {
            count++;
            return new Object();
        }
    }
}

private BuildThreeObjects bto;

@Before
public void setUp() throws Exception {
    bto = new BuildThreeObjects();
}

@Test
public void testBuild() {
    assertNotNull(bto.buildObject());
    System.out.println(bto.count);
    assertNotNull(bto.buildObject());
    System.out.println(bto.count);
    assertNotNull(bto.buildObject());
    System.out.println(bto.count);
    assertNull(bto.buildObject());
    System.out.println(bto.count);
}

// 带有for循环

for(int i=0; i < 100; i++){
        if(i < 3){
            assertNotNull(bto.buildObject());
            System.out.println(bto.count);
        } else {
             assertNull(bto.buildObject());
               System.out.println(bto.count);
        }
    }
于 2013-07-30T10:20:52.267 回答
1

只是从字面上做到这一点:

assertNotNull(createObject());

assertNotNull(createObject());

assertNotNull(createObject());

assertNull(createObject());

如果它可以更具表现力,您也可以使用 for-loop。

于 2013-07-30T09:56:19.997 回答