0

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

            }
    }

}
4

1 回答 1

6

You're not creating an instance of the class under test, you're only declaring it as the interface. In each of your tests you should create an instance of the class under test and test it's implementation of the method. Note also, your tests should not be dependent on one another. You shouldn't rely on them running in particular order; any set up for a test should be done in the test set up method, not by another test.

Generally you want to use the AAA (Arrange, Act, Assert) pattern in your tests. The setUp (arrange) and tearDown (assert) can be part of this, but the pattern should also be reflected in each test method.

@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
}
于 2012-06-17T14:22:33.000 回答