Java JUnit测试-我做错了什么
我对JUnit测试非常陌生,我正在尝试测试以下非常简单的类Java JUnit测试-我做错了什么,java,junit,Java,Junit,我对JUnit测试非常陌生,我正在尝试测试以下非常简单的类 public interface IItemsService extends IService { public final String NAME = "IItemsService"; /** Places items into the database * @return * @throws ItemNotStoredException */ public boolean
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(排列、动作、断言)模式。设置(排列)和拆卸(断言)可以是其中的一部分,但是模式也应该反映在每个测试方法中
@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
}
您没有创建被测试类的实例,您只是将其声明为接口。在每个测试中,您都应该创建被测试类的实例,并测试其方法的实现。另外请注意,您的测试不应该相互依赖。你不应该依赖于他们按照特定的顺序运行;测试的任何设置都应在测试设置方法中进行,而不是通过另一个测试进行 通常,您希望在测试中使用AAA(排列、动作、断言)模式。设置(排列)和拆卸(断言)可以是其中的一部分,但是模式也应该反映在每个测试方法中
@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
}
谢谢-下半部分对我来说很有意义,但我不太明白你所说的someDependency/serviceDependency是什么意思,你能详细说明一下吗?很抱歉,我今天显然是太密集了。谢谢你-下半部分对我来说很有意义,但我不太明白你所说的someDependency/serviceDependency是什么意思,你有没有可能详细说明一下?对不起,我今天显然是超浓的。