JUnit - 测试最大创建对象数

时间:2013-07-30 09:53:16

标签: java junit assert

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

2 个答案:

答案 0 :(得分: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);
}

// with for loop

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);
        }
    }

答案 1 :(得分:1)

按字面意思做:

assertNotNull(createObject());

assertNotNull(createObject());

assertNotNull(createObject());

assertNull(createObject());

如果它更具表现力,你也可以使用for循环。