繁体   English   中英

JUnit测试-我在做什么错

[英]JUnit Testing - What am I doing Wrong

我对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;

}

这就是我要进行的测试,但是我一直得到空指针,并且关于它的另一个错误不适用于该参数……显然我在做一些愚蠢的事情,但是我没有看到它。 有人可以指出我正确的方向吗?

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

            }
    }

}

您不是在创建要测试的类的实例,而只是将其声明为接口。 在每个测试中,您都应创建被测类的实例,并测试该方法的实现。 另请注意,您的测试不应相互依赖。 您不应该依赖于它们以特定顺序运行; 测试的任何设置均应使用测试设置方法进行,而不要通过其他测试进行。

通常,您想在测试中使用AAA(排列,执行,声明)模式。 setUp(安排)和tearDown(声明)可以是其中的一部分,但是该模式也应该在每种测试方法中得到反映。

@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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM