【问题标题】:mockito - mocking an interface - throwing NullPointerExceptionmockito - 模拟接口 - 抛出 NullPointerException
【发布时间】:2013-10-30 16:52:53
【问题描述】:

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

    //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<Pet> listPets();
    }

    // a client code using the PetService to list Pets
    public class App {
        PetService petService;

        public void listPets() {
             // TODO Auto-generated method stub
             List<Pet> 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<Pet> listPets = app.listPets();
            Pet[] pet = new Dog[]{new Dog(1,"puppy")};
            List<Pet> 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 代码进行了模拟。你能帮我解决这个问题吗?

【问题讨论】:

  • 你需要在你的App中注入mock,否则调用listPets()时App.petService会为null
  • 你可以使用 Mock 和 InjectMocks 注释 - 更多细节在这里stackoverflow.com/questions/19580197/…
  • Chris 回答的最简单的方法是构造函数/设置器,但您也可以使用 Mockito 的 @InjectMocks:docs.mockito.googlecode.com/hg/latest/org/mockito/…。首先阅读 Mockito 文档可能是个好主意,因为它很好地解释了事情是如何工作的。

标签: java android mockito


【解决方案1】:

你也可以使用@InjectMocks注解,这样你就不需要任何getter和setter了。只需确保在注释类后在测试用例中添加以下内容,

@Before
public void initMocks(){
    MockitoAnnotations.initMocks(this);
}

【讨论】:

    【解决方案2】:

    NullPointerException 是因为在 App 中,petService 在尝试使用之前没有实例化。要注入 mock,在 App 中添加这个方法:

    public void setPetService(PetService petService){
        this.petService = petService;
    }
    

    然后在你的测试中,调用:

    app.setPetService(petService);
    

    运行前app.listPets();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多