JUnit测试 - 我做错了什么

Exp*_*cto 0 java junit

我是JUnit测试的新手,我正在尝试测试以下非常简单的类

public interface IItemsService extends IService {

    public final String NAME = "IItemsService";


    /** Places items into the database
     * @return 
     * @throws ItemNotStoredException 
    */
    public boolean storeItem(Items items) throws ItemNotStoredException;




    /** Retrieves items from the database
     * 
     * @param category
     * @param amount
     * @param color
     * @param type
     * @return
     * @throws ItemNotFoundException 
     */
    public Items getItems (String category, float amount, String color, String type) throws ItemNotFoundException;

}
Run Code Online (Sandbox Code Playgroud)

这是我的测试,但我一直得到空指针,另一个错误,它不适用于参数...显然我做了一些愚蠢但我没有看到它.有人能指出我正确的方向吗?

public class ItemsServiceTest extends TestCase {



    /**
     * @throws java.lang.Exception
     */

    private Items items;

    private IItemsService itemSrvc;

    protected void setUp() throws Exception {
        super.setUp();

        items = new Items ("red", 15, "pens", "gel");

    }

    IItemsService itemsService;
    @Test
    public void testStore() throws ItemNotStoredException {
            try {
                Assert.assertTrue(itemSrvc.storeItem(items));
            } catch (ItemNotStoredException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println ("Item not stored");
            }
    }

    @Test
    public void testGet() throws ItemNotStoredException {
            try {
                Assert.assertFalse(itemSrvc.getItems(getName(), 0, getName(), getName()));
            } catch (ItemNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
    }

}
Run Code Online (Sandbox Code Playgroud)

tva*_*son 6

您没有创建被测试类的实例,您只是将其声明为接口.在每个测试中,您应该创建一个被测试类的实例,并测试它的方法实现.另请注意,您的测试不应相互依赖.你不应该依赖它们按特定顺序运行; 任何测试设置都应该在测试设置方法中完成,而不是通过其他测试.

通常,您希望在测试中使用AAA(排列,动作,断言)模式.setUp(arrange)和tearDown(assert)可以是其中的一部分,但模式也应该反映在每个测试方法中.

@Test
public void testStore() throws ItemNotStoredException {
    // Arrange
    ISomeDependency serviceDependency = // create a mock dependency
    IItemsService itemSvc = new ItemsService(someDependency);

    // Act
    bool result = itemSrvc.storeItem(items);

    // Assert
    Assert.assertTrue(result);
    // assert that your dependency was used properly if appropriate
}
Run Code Online (Sandbox Code Playgroud)