简体   繁体   English

模拟DAO类及其中的方法

[英]Mock a DAO class and a method within it

I am trying to mock a DAO class that has a method which returns a list of a specific class. 我试图模拟一个DAO类,该类具有一种返回特定类列表的方法。

private List<SpecificClass> getInfo(){

List<SpecificClass> returnInformation = dao.list(ParamOne, Param Two, SpecificClass.class);
}

The dao mentioned in the above method refers to another class. 上述方法中提到的dao是指另一类。

I begin by mocking that DAO class. 我首先嘲笑该DAO类。

Mockito.mock(TheDaoClass.class);

and creating a mocked list 并创建一个模拟列表

private @Mock List<SpecificClass> returnedList = new ArrayList<SpecificClass>();

Then I make call to that method 然后我调用该方法

dao.list(ParamOne, Param Two, SpecificClass.class);

and specify what needs to be done when it is called 并指定调用时需要执行的操作

when(dao.list(ParameterOne, anyString(), SpecificClass.class)).thenReturn(returnedList);

When I do the above I get a null pointer exception. 当我做上面的时候,我得到一个空指针异常。 There can be two causes: 可能有两个原因:

I understand the list is empty but all it is supposed is hold SpecificClass's five values but that shouldn't throw an error at this point. 我知道列表是空的,但应该假设它仅包含SpecificClass的五个值,但此时不应抛出错误。

I think object dao is not getting mocked properly. 我认为对象dao没有得到适当的嘲笑。 I am only mocking the whole class Mockito.mock(TheDaoClass.class) in order to mock any object asociated with that class. 我只在模拟整个类Mockito.mock(TheDaoClass.class)以便模拟与该类关联的任何对象。 I think that it is not achieving the objective. 我认为这没有实现目标。 how do I go about solving this problem? 我该如何解决这个问题? Any help is appreciated. 任何帮助表示赞赏。 Thanks. 谢谢。

Make your mocked DAO object a property of your test class like so: 使模拟的DAO对象成为测试类的属性,如下所示:

@Mock
private TheDaoClass mockDaoClass;

Then, in your setUp() method at the beginning of your test class call initMocks : 然后,在测试类开始的setUp()方法中,调用initMocks

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

This should prevent the NullPointer . 这应该防止NullPointer

Additionally, I recommend that rather than mock the List object (if you are mocking any Java library data type you are probably doing it wrong), you should create a list and populate it. 另外,我建议不要模拟List对象(如果模拟任何Java库数据类型,则可能做错了),应该创建一个列表并填充它。

List<SpecificClass> list = new ArrayList<SpecificClass>();
list.add(new SpecificClass());

Then return the list from the mocked method. 然后从模拟方法返回列表。

when(mockDaoClass.list(anyString(), anyString(), SpecificClass.class)).thenReturn(list);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM