[英]Unit testing a class that calls out to external service
I have the following class: 我有以下课程:
public class SomeClass {
private Dependency dependency;
public SomeClass(Dependency dep){
this.dependency = dep;
}
public void doSomething(String s){
Foo f = dependency.getFoo(s);
f.doWork(); // fails because f is null
}
}
I am trying to write a unit tests that will cover the doSomething method in which getFoo is an external call that I am trying to mock as follows: 我正在尝试编写一个单元测试,以涵盖doSomething方法,其中getFoo是我尝试模拟的外部调用,如下所示:
@Mock
private Dependency dep;
@InjectMocks
private SomeClass _sc;
@Test
public void testSimple() {
Foo ff = new Foo();
when(dep.getFoo("abc")).thenReturn(ff);
SomeClass sc = new SomeClass();
sc.doSomething("abc"); // fails on null pointer exception
}
Unfortunately, I am getting a null reference exception in my unit test - since the mock class isn't being returned. 不幸的是,在单元测试中我得到了一个空引用异常-因为没有返回模拟类。 How can I fix it?
我该如何解决?
You should use 你应该用
_sc.doSomething("abc");
not sc.doSomething("abc");
不是
sc.doSomething("abc");
First make sure your test class is annotated with MockitoJUnitRunner. 首先,确保您的测试类使用MockitoJUnitRunner进行了注释。
@RunWith(MockitoJUnitRunner.class)
Second, in your test, you should use your target test class "_sc" which gets injected with the mocks. 其次,在测试中,应使用目标测试类“ _sc”,该类将被注入模拟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.