Liferay Junit-Mockito 测试
我正在尝试使用 JUNIT 和 Mockito 测试我的 liferay portlet 插件代码。目前,我正在模拟服务实现以返回模拟数据并测试功能。
我面临的问题是,我需要测试一些将属性视为: PropsUtil.get("someKey") 但是当我将其作为独立的 JUNIT 测试运行时,PropsUtil 不会从任何属性文件中读取。 有什么方法可以让测试从 liferay 属性(portal*.properties)文件中读取而不更改源代码?
I am trying to test my liferay portlet plugin code using JUNIT and Mockito. Currently I am mocking the service implementations to return mock data and test the functionalities.
The problem I am facing is, I need to test some code which takes properties as :
PropsUtil.get("someKey")
But when i run it as a standalone JUNIT test, PropsUtil is not reading from any of the properties file.
Is there any way I can make the test read from the liferay properties (portal*.properties) file without changing the source code ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我使用了以下方法:
在这种情况下,liferay 加载所有属性以及 spring 初始化。
I used the following method :
In this case, liferay loads all the properties as well as does the spring initializations.
您可以创建基于
Props
接口的Properties
实现:然后使用
@BeforeClass
来配置它:You can create a
Properties
based implementation of theProps
interface:Then use an
@BeforeClass
to configure it:作为最后的手段,您可以使用 PowerMock 和模拟
PropsUtil.get()方法调用。最终它是一个普通的旧java单例,并且带有单例的代码并不那么容易测试。
As the last resort you could use PowerMock and mock
PropsUtil.get()
method call. Eventually it's a plain-old-java-singleton and code with singletons is not that easy to test..除非您正在测试 Portal.properties 中实际设置的值,否则只需在测试中调用 PropsUtil.set 即可。
Unless you're testing that values are actually set in portal.properties, just call PropsUtil.set in your test.
您还可以像这样模拟调用:
You can also mock the call like this:
你需要调用 InitUtil.init() 来初始化基本的基础设施,属性包括...
如果你想更进一步并启动 spring 基础设施,你需要在类路径上有 liferay 库。我在这篇博文中解释了如何在 Maven 环境中执行此操作: 如何在maven插件SDK中使用liferay第三方库。如果您这样做,那么您需要做的就是使用门户 spring xml 定义(基础设施 + 那些您需要使用的 spring 服务)设置 spring.configs 并调用
Init.initWithSpring();
它负责启动 liferay 门户,并使用您在 spring.configs 中混合的 Spring beans。您还需要稍微修改 liferay 属性。但这实际上取决于用例。you need to call InitUtil.init() which initializes the basic infrastructure, properties including ...
If you wanted to go further and boot up even the spring infrastructure, you'd need to have liferay libraries on classpath. I'm explaining how to do that in maven environment in this blog post : how to use liferay third-party libraries in maven plugin SDK. If you do so, then all you need to do is to setup spring.configs with portal spring xml definitions (infrastructure ones + those with spring services that you need to use) and call
Init.initWithSpring();
that takes care of booting up liferay portal and it uses those spring beans that you mix up in spring.configs. You also would need to modify liferay properties a little. But it really depends on the use case.