[英]How to mock org.springframework.core.io.Resource object?
In my service method, I have a dependency on org.springframework.core.io.Resource
reference and I want to write a test case for one of service method with below code在我的服务方法中,我依赖于
org.springframework.core.io.Resource
参考,我想用下面的代码为服务方法之一编写一个测试用例
The code below is as follows:下面的代码如下:
@Service
public class EmailServiceImpl implements EmailService{
@Value("classpath:email_template.html")
private Resource emailTemplateResource;
private String getEmailTemplate() {
String template = null;
try {
template = new BufferedReader(new InputStreamReader(emailTemplateResource.getInputStream()))
.lines().collect(Collectors.joining("\n"));
} catch (IOException e) {
e.printStackTrace();
}
return template;
}
}
Here, I'm not able to mock emailTemplateResource
object in my test case method.在这里,我无法在我的测试用例方法中模拟
emailTemplateResource
object。 I tried with @Mock
and @Spy
but each time I'm getting NullPointerException on emailTemplateResource
object.我尝试使用
@Mock
和@Spy
,但每次我在emailTemplateResource
object 上收到 NullPointerException。
So, what is the right way to mock this emailTemplateResource
object?那么,模拟此
emailTemplateResource
object 的正确方法是什么?
You can do constructor injection in EmailServiceImpl
.您可以在
EmailServiceImpl
中进行构造函数注入。 That way in your mock class when create EmailServiceImpl
you can pass your own Resource
object in the constructutor.这样,在您的模拟 class 创建
EmailServiceImpl
时,您可以在构造函数中传递您自己的Resource
object 。
The overhead with this approach is that @InjectMocks
is of no use as now you are creating your object on your own inside before
hook of the test case.这种方法的开销是
@InjectMocks
没有用,因为现在您在测试用例挂钩before
在自己的内部创建 object。
example:例子:
@RunWith(MockitoJUnitRunner.class)
public class EmailServiceImplTest{
EmailServiceImpl emailServiceImpl ;
Resource emailTemplateResource;
@Before
public void before() {
emailTemplateResource = //your impl here
emailServiceImpl = new EmailServiceImpl(resource);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.