我有一些 EJB 作为 JAX-WS Web 服务:
@WebService
@Stateless
@Remote(MobileFacade.class)
public class MobileFacadeBean implements MobileFacade {
...
@Resource
WebServiceContext wsc;
...
}
在此 Web Service 类中,通过 @Resource 注入(inject) WebServiceContext。我使用此 WebServiceContext 来获取实现中的主体。这工作得很好,但现在我想知道如何(单元)测试这个类!
到目前为止,我正在使用 OpenEJB 来测试我的 EJB。由于 Web Service 类也是一个无状态 session Bean,因此我真的很想在这里使用相同的方法。然而,它的工作并不那么容易 - 当然,它会提示当不作为 Web 服务调用时没有 WebServiceContext。
所以第一个问题是:有没有办法在 OpenEJB 中模拟 WebServiceContext?
如果不是,您喜欢用什么方法来测试这种 Web 服务类?
干杯, 弗兰克
最佳答案
OpenEJB 示例 zip 文件中有一些 @WebService
单元测试示例。你想要的一切都应该可以正常工作。
webservice-security 示例听起来与您想要的完全一样。网上的版本是使用@RolesAllowed
让容器做安全检查,而不是用代码来做,但是可以用代码来检查原理。这是该示例的稍微修改后的版本,对我来说没有任何问题。
bean
@DeclareRoles(value = {"Administrator"})
@Stateless
@WebService(
portName = "CalculatorPort",
serviceName = "CalculatorWsService",
targetNamespace = "http://superbiz.org/wsdl",
endpointInterface = "org.superbiz.calculator.CalculatorWs")
public class CalculatorImpl implements CalculatorWs, CalculatorRemote {
@Resource
private WebServiceContext webServiceContext;
@RolesAllowed(value = {"Administrator"})
public int sum(int add1, int add2) {
// maybe log the principal or something -- prints "jane" in the test
System.out.print(webServiceContext.getUserPrincipal());
return add1 + add2;
}
@RolesAllowed(value = {"Administrator"})
public int multiply(int mul1, int mul2) {
return mul1 * mul2;
}
}
测试
public class CalculatorTest extends TestCase {
private InitialContext initialContext;
protected void setUp() throws Exception {
Properties properties = new Properties();
properties.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
properties.setProperty("openejb.embedded.remotable", "true");
initialContext = new InitialContext(properties);
}
/**
* Create a webservice client using wsdl url
*
* @throws Exception
*/
public void testCalculatorViaWsInterface() throws Exception {
URL url = new URL("http://127.0.0.1:4204/CalculatorImpl?wsdl");
QName calcServiceQName = new QName("http://superbiz.org/wsdl", "CalculatorWsService");
Service calcService = Service.create(url, calcServiceQName);
assertNotNull(calcService);
CalculatorWs calc = calcService.getPort(CalculatorWs.class);
((BindingProvider) calc).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "jane");
((BindingProvider) calc).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "waterfall");
assertEquals(10, calc.sum(4, 6));
assertEquals(12, calc.multiply(3, 4));
}
}
库
如果使用 Maven,请将正常的 openejb-core
依赖项切换为 openejb-cxf
,如下所示。这会将 Apache CXF 和 OpenEJB/CXF 集成代码添加到您的类路径中。
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>openejb-cxf</artifactId>
<version>3.1.4</version>
<scope>test</scope>
</dependency>
如果不使用 maven,最简单的方法是添加 OpenEJB zip 文件的 lib/
目录中的所有 jar。
关于web-services - 使用 WebServiceContext 测试 @Webservice EJB(使用 OpenEJB?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6175879/