I am using WebSphere Liberty 8.5.5 server and writing some batch test cases on this server. I am trying to mock jndi lookup object for testing but while setting up dataSource object in test case I am getting below error, Does anyone know how to set INITIAL_CONTEXT_FACTORY
ERROR : javax.naming.NoInitialContextException: Need to specify class name in environment or system prop
erty, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
You need to set the class name of your initial context factory in the environment of the InitialContext constructor.
For example:
Hashtable<Object, Object> env = new Hashtable<>();
env.put(InitialContext.INITIAL_CONTEXT_FACTORY, "com.example.MockICF");
new InitialContext(env);
Where com.example.MockICF might be written as:
public class MockICF implements InitialContextFactory {
private static Context ctx = new Mockery().mock(Context.class);
#Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
return ctx;
}
}
Related
I am using the CakePHP-ReST-DataSource-Plugin Datasource for hitting a RESTful service in my model. This implies that the models will not have a database connection.
I have successfully accessed the services and would now like to write unit tests for the models. This is proving to be a daunting task since I cannot succeed to mock the datasource so that I do not hit the actual remote Service but rather return expected results for the tests.
<?php
App::uses('KnowledgePoint', 'Model');
class KnowledgePointTest extends CakeTestCase{
public $fixtures = array('app.knowledgepoint');
public $useDbConfig = 'RestTest';
private $KnowledgePoint;
public function setUp() {
parent::setUp();
$this->KnowledgePoint = ClassRegistry::init('KnowledgePoint');
/**
* This is the confusing part. How would I mock the datasource
so that I can mock the request method which returns the data
from the api?
*/
$this->KnowledgePoint->DataSource = $this->getMockForModel(
'RestSource',array('request'));
}
public function tearDown() {
parent::tearDown();
}
}
I would like to be able to mock the datasource and stub the request method to return data that would normally be returned from the remote service.
Kind regards,
Roland
Mocking the model and its getDataSource() method so that it returns your mocked datasource should theoretically work. Here's an example
App::uses('RestSource', 'Rest.Model/Datasource');
$DataSource = $this->getMock('RestSource', array('request'), array(array()));
$DataSource
->expects($this->any())
->method('request')
->will($this->returnValue('some custom return value'));
$Model = $this->getMockForModel('KnowledgePoint', array('getDataSource'));
$Model
->expects($this->any())
->method('getDataSource')
->will($this->returnValue($DataSource));
$Model->save(/* ... */);
In case you are wondering about the array(array()) for the datasource mock, this is required as the RestSource constructor doesn't supply a default value for the first argument (unlike the parent constructor).
in my services folder, i have this file
abstract class AsyncUploadedFileService<T> {
def grailsApplication
def jesqueService
String jobName
String workerPool
String _queueName
AsyncUploadedFileService (Class<T> job, String workerPool) {
jobName = job.simpleName
this.workerPool = workerPool
}
}
and I have a unit test
#Build(UploadedFile)
#TestMixin(GrailsUnitTestMixin)
#TestFor(AsyncUploadedFileService)
class AsyncUploadedFileServiceSpec extends Specification {
def setup() {
User.metaClass.encodePassword = {-> }
}
void "add to the worker pool"() {
when:
UploadedFile uploadedFile = UploadedFile.build()
then:
service.perform(uploadedFile)
}
}
when I run my test, I get the following error
Cannot add Service class [class com.example.AsyncUploadedFileService]. It is not a Service!
org.codehaus.groovy.grails.exceptions.GrailsConfigurationException: Cannot add Service class [class com.example.AsyncUploadedFileService]. It is not a Service!
at grails.test.mixin.services.ServiceUnitTestMixin.mockService(ServiceUnitTestMixin.groovy:46)
at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:138)
at org.spockframework.runtime.extension.builtin.JUnitFixtureMethodsExtension$FixtureType$FixtureMethodInterceptor.intercept(JUnitFixtureMethodsExtension.java:145)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:84)
at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:138)
at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:138)
at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:138)
Is this error because I'm using the service.perform() syntax? If so, what other way is there of testing the AsynchUploadedFileService function?
You can't instantiate an abstract class, so you can't create one to test with. Make it non-abstract, or create a concrete subclass and test that.
Also, since you have a constructor with arguments, there is no default (no-arg) constructor. If you have no constructors, the compiler adds one for you (in both Java and Groovy) and in Grails since services are auto-registered, you must have a no-arg constructor (you can have others, but I can't see why you would) so Spring can create the instance. You can always manually wire up a class as a Spring bean and provide constructor args in resources.groovy, but then it wouldn't be a Grails service, so it would be better to put it in src/groovy.
Grails 2.2.0
How do I access the custom configuration variables in a Grails domain object constraints.
I would like to have something like this:
class User {
def grailsApplication
String name
static constraints = {
name size: grailsApplication.config.maxlength
}
}
But it fails with "No such property: grailsApplication". I have tried to get it work by following suggestions in getting grails 2.0.0M1 config info in domain object, and static scope? but have not managed to get any combination to work.
How do I access config in domain object constraints? In addition how do I handle such a case in a unit test for the domain constraints?
You can use the grails.util.Holders class to get access to the configuration object as follows:
In Config.groovy:
myMaxSize = 10
In your domain class:
class User {
String name
static constraints = {
name minSize: Holders.config.myMaxSize
}
}
I have some EJBs as JAX-WS Web Service:
#WebService
#Stateless
#Remote(MobileFacade.class)
public class MobileFacadeBean implements MobileFacade {
...
#Resource
WebServiceContext wsc;
...
}
Within this Web Service class, a WebServiceContext is injected via #Resource. I use this WebServiceContext to get the principal in the implementation. This works quite well, but now I wonder how to (Unit-)test this class!
So far, I was using OpenEJB to test my EJBs. Since the Web Service class also is an Stateless Session Bean, I would really like to use the same approach here. However, it does not work that easy - of course, it complains that there is no WebServiceContext when not called as a Web Service.
So the first question is: are there any ways to mock the WebServiceContext in OpenEJB?
And if no, what approach would you favour to test this kind of Web Service classes?
Cheers,
Frank
There are a handful of #WebService unit test examples in the OpenEJB examples zip file. Everything you want should work fine.
simple-webservice
webservice-attachments
webservice-security
webservice-ws-security
The webservice-security example sounds exactly like what you want. The version online uses #RolesAllowed to make the container do the security check rather than doing it in code, but it is possible to check the principle in code. Here's a slightly modified version of that example that worked for me with no issues.
The 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;
}
}
The Test
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));
}
}
Libraries
If using maven, switch your normal openejb-core dependency to openejb-cxf like so. This will add Apache CXF and the OpenEJB/CXF integration code to your classpath.
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>openejb-cxf</artifactId>
<version>3.1.4</version>
<scope>test</scope>
</dependency>
If not using maven, simplest approach is to just add all the jars from the lib/ directory of the OpenEJB zip file.
David,In your answer in CalculatorTest you have used CalculatorWs.class, Is it same interface as it is used in webservice side implementation. Do we have to create web service client?
Also in David's example Instead of
QName calcServiceQName = new QName("http://superbiz.org/wsdl", "CalculatorWsService");
use
QName calcServiceQName = new QName("http://superbiz.org/wsdl", "CalculatorPort");
I'm having hard time mocking the save instance method in my unit tests in Grails 1.3.3. I've created a simple domain class named Person, it has one property (nullable) called "name".
package tutorial
class Person {
String name
static constraints = {
name nullable: true
}
}
In my test I'm trying to do something I've found in the documentation:
class PersonTests extends GrailsUnitTestCase {
public void testCanSavePerson() {
def testInstances = []
mockDomain(Person, testInstances)
assertEquals(0, Person.count())
new Person(name: "Bob").save()
assertEquals(1, Person.count())
}
}
However as soon as I run the test what I get is an exception:
java.lang.NullPointerException
at grails.test.MockUtils$_addValidateMethod_closure83.doCall(MockUtils.groovy:973)
at grails.test.MockUtils$_addValidateMethod_closure84.doCall(MockUtils.groovy:1014)
at grails.test.MockUtils$_addDynamicInstanceMethods_closure67.doCall(MockUtils.groovy:736)
at grails.test.MockUtils$_addDynamicInstanceMethods_closure67.doCall(MockUtils.groovy)
at tutorial.PersonTests.testCanSavePerson(PersonTests.groovy:25)
whereas the line 25 is exactly the one that calls save() on newly created instance.
Does anyone knows what am I doing wrong?
This is an already known bug in Grails 1.3.3. Read more about it and find a workaround in the associated JIRA ticket GRAILS-6482.