如何模拟私有dao变量? [英] How to mock a private dao variable?

查看:70
本文介绍了如何模拟私有dao变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在测试方法时模拟的dao.create()调用. 但由于仍在获得NPE,我缺少了一些东西.怎么了?

I have a dao.create() call that I want to mock when testing a method. But I am missing something as I'm still getting NPE. What is wrong here?

class MyService {
    @Inject
    private Dao dao;

    public void myMethod() {
        //..
        dao.create(object);
        //
    }
}

如何模拟出dao.create()调用?

How can I mock out the dao.create() call?

@RunWith(PowerMockRunner.class)
@PrepareForTest(DAO.class)
public void MyServiceTest {

    @Test
    public void testMyMethod() {
        PowerMockito.mock(DAO.class);

        MyService service = new MyService();
        service.myMethod(); //NPE for dao.create()
    }
}

推荐答案

您没有在注入DAO.使用嘲笑,您可以将测试类更改为使用@InjectMocks并使用嘲笑赛跑者.

You are not injecting the DAO. With mockito you can change your test class to use @InjectMocks and use mockito runner.

@RunWith(MockitoJUnitRunner.class)
public void MyServiceTest {
    @Mock
    private Dao dao;
    @InjectMocks
    private MyService myService;
    ...
}

您可以在 Inject Mocks API上了解有关InjectMocks的更多信息

更简单的方法是将构造函数的注入方式更改为注入方式.例如,您可以将MyService更改为

Simpler way is changing your injection to injection by constructor. For example, you would change MyService to

class MyService {
    ...
    private final Dao dao;

    @Inject
    public MyService(Dao dao) {
        this.dao = dao;
    } 
    ...
}

然后,您可以在设置中简单地通过模拟的DAO.

then your test you could simple pass the mocked DAO in setup.

...
@Mock
private Dao dao;

@Before
public void setUp() {
    this.dao = mock(Dao.class);
    this.service = new MyService(dao);
}
...

现在您可以使用verify来检查是否调用了create,例如:

now you can use verify to check if create was called, like:

...
   verify(dao).create(argThat(isExpectedObjectBeingCreated(object)));
}

private Matcher<?> isExpectedObjectBeingCreated(Object object) { ... }

使用构造函数注入将使您的依赖关系对其他开发人员更加清晰,并且在创建测试时会有所帮助:)

Using injection by constructor will let your dependencies clearer to other developers and it will help when creating tests :)

这篇关于如何模拟私有dao变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆