java 接口 空指针_java – mockito – 模拟接口 – 抛出NullPointerException

我也在模拟后得到空指针异常.请找到我的项目结构.

//this is the pet interface

public interface Pet{

}

// An implementation of Pet

public class Dog extends Pet{

int id,

int petName;

}

// This is the Service Interface

public interface PetService {

List listPets();

}

// a client code using the PetService to list Pets

public class App {

PetService petService;

public void listPets() {

// TODO Auto-generated method stub

List listPets = petService.listPets();

for (Pet pet : listPets) {

System.out.println(pet);

}

}

}

// This is a unit test class using mockito

public class AppTest extends TestCase {

App app = new App();

PetService petService = Mockito.mock(PetService.class);

public void testListPets(){

//List listPets = app.listPets();

Pet[] pet = new Dog[]{new Dog(1,"puppy")};

List list = Arrays.asList(pet);

Mockito.when(petService.listPets()).thenReturn(list);

app.listPets();

}

}

我在这里尝试使用TDD,意味着我已经编写了服务接口,但不是实际的实现.为了测试listPets()方法,我清楚地知道它使用该服务来获取宠物列表.但我的意图是在这里测试App类的listPets()方法,因此我试图模拟服务接口.

App类的listPets()方法使用该服务来获取宠物.所以我用mockito嘲笑那个部分.

Mockito.when(petService.listPets()).thenReturn(list);

但是当单元测试运行时,perService.listPets()抛出NullPointerException,我已经使用上面的Mockito.when代码进行了模拟.你能帮帮我吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值