[英]Junit/Mockito how to mock an object called from class b which is called from class a
I have a class called a, which mocks a class b.我有一个名为 a 的类,它模拟了一个类 b。
Class b has a method which is creating an object by calling a data access object (DAO) c.类 b 具有通过调用数据访问对象 (DAO) c 创建对象的方法。 That is,
a.method1 -> b.method2
which internally calls c.getdata()
.也就是说,
a.method1 -> b.method2
在内部调用c.getdata()
。
When I try to create a unit test I get object c is null.当我尝试创建单元测试时,我得到对象 c 为空。 How do I resolve this issue?
我该如何解决这个问题?
class Alpha {
String abc;
Beta beta = new Beta();
List<String> seriesOfStgs = new ArrayList<>();
public void alphaMethod() {
seriesOfStgs.addAll(beta.getStrings());
}
}
class Beta {
StringDao stringDao = new StringDao();
public List<String> getStrings() {
return stringDao.getListOfStrings();
}
}
If you see above, I have 2 separate classes Alpha
and Beta
.如果您在上面看到,我有 2 个单独的类
Alpha
和Beta
。 I am writing the test for Alpha
.我正在为
Alpha
编写测试。 I am able to mock Beta
in my JUnit test, TestAlpha.java
.我能够在我的 JUnit 测试
TestAlpha.java
中模拟Beta
。 I am getting a null pointer exception when I try to get the strings because stringDao
is null.当我尝试获取字符串时出现空指针异常,因为
stringDao
为空。
How do I instantiate stringDao
in TestAlpha
, or how do I pass a reference to StringDao
?如何在
TestAlpha
中实例化stringDao
,或者如何传递对StringDao
的引用?
You need to find a way of injecting your Beta
mock into the Alpha
object that you're testing.您需要找到一种方法将您的
Beta
模拟注入您正在测试的Alpha
对象。 Otherwise, your Alpha
object will just have the Beta
that was created at the line否则,您的
Alpha
对象将只具有在该行创建的Beta
Beta beta = new Beta();
One way to do that would be to have a setBeta
method in your Alpha
class, which you could then call in your test.一种方法是在您的
Alpha
类中使用setBeta
方法,然后您可以在测试中调用该方法。
Another way would be to refactor your Alpha
class so that it gets its Beta
object from a factory, and then inject the factory when you construct the Alpha
object.另一种方法是重构您的
Alpha
类,以便它从工厂获取其Beta
对象,然后在您构造Alpha
对象时注入工厂。 This is "pattern 2" in my article here这是我的文章中的“模式 2”
Beta
can be also mock object. Beta
也可以是模拟对象。
for example例如
@Mock
Alpha alpha;
@Mock
Beta beta;
...
when(alpha.getBeta()).thenReturn(beta); // now you get mocked beta from alpha
when(beta.getStrings()).thenReturn("mock string");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.