how to get getPooledConnection() on MysqlConnectionPoolDataSource - junit

I have a class where i want the pool connection . I created MysqlConnectionPoolDataSource object and on that i'm calling the getPooledConnection() method like this
MysqlConnectionPoolDataSource datasource;
PooledConnection pconn=null;
pconn = dataSource.getPooledConnection();
when i am run the test class i am unable to get ant thing in
pconn = dataSource.getPooledConnection(); That is dataSource.getPooledConnection() returning nothing. How to fix this issue.
Thanks

Since you are using MysqlConnectionPoolDataSource in a test and not a Java EE container, you need to configure the object. At the very least I appears you will need to call setUrl(), setUser() and setPassword()

Related

easymock two setAttributes for one session

I have created a session in the test class. and return it when getsession is called.
expect(request.getSession()).andReturn(session);
I have set two different attributes for the session as they are set in the method which I want to test.
session.setAttribute("name","xyz");
session.setAttribute("class", "A")'
When I call the method, in the when it tries to setAttribue, it causes a nullpointerexception.
Any help?
It can be problem if you set the values after making expect method.
User user=new User();
expect(mock.getUser()).andReturn(user);
user.setName("John"); //It should be above the expect line
Or you forget to call EasyMock replay() method on your mock after expect method.
// Setup the method of mock object
expect(mock.getNum()).andReturn(2)
// Setup is finished need to activate the mock
replay(mock);

Zend: Accessing model from Bootstrap raises an exception

This is the code I have in Bootstrap:
public function _initRegistry()
{
$systemConfigModel = new Application_Model_DbTable_SystemConfig();
Zend_Registry::set('config', $systemConfigModel->getSystemConfig());
}
And this an exception I am getting:
( ! ) Fatal error: Uncaught exception 'Zend_Db_Table_Exception' with message 'No adapter found for Application_Model_DbTable_SystemConfig' in /usr/share/php5/Zend/Db/Table/Abstract.php on line 755
( ! ) Zend_Db_Table_Exception: No adapter found for Application_Model_DbTable_SystemConfig in /usr/share/php5/Zend/Db/Table/Abstract.php on line 755
It works just fine if I call it within my BaseController. It just looks like the PDO adapter that I specify in application.ini has not been initialized at the time Bootstrap is executed (strange?). What should I do to make the code work in Bootstrap? Is it necessary to create and set an adapter with Zend_Db_Table::setDefaultAdapter();?
I am asking because if the code is not in Bootstrap, it needs to be duplicated in two different places and it also kind of looks like it belongs to Bootstrap.
You are correct, during bootstrap, the Zend Application resource for your database has not yet been initialized.
Try changing your bootstrap method as follows so you explicitly bootstrap the db resource.
public function _initRegistry()
{
$this->bootstrap('db'); // Bootstrap the db resource from configuration
$db = $this->getResource('db'); // get the db object here, if necessary
// now that you have initialized the db resource, you can use your dbtable object
$systemConfigModel = new Application_Model_DbTable_SystemConfig();
Zend_Registry::set('config', $systemConfigModel->getSystemConfig());
}

NUnit / Moq throwing a NullReferenceException error on the constructor of a variable

I am using Moq, NUnit, WPF, MVVM, Ninject.
I am writing a test for my LoginViewModel, and in the test when I use the constructor of the LoginViewModel to create a new instance, I am getting a NullReferenceException error. The code compiles and runs, (i.e. when I run the program the LoginView shows, and works with the LoginViewModel to create the correct behaviour etc) but for some reason the UnitTest is crashing.
this is the constructor:
public LoginViewModel(ILoginServices loginServices,IDialogService dialogServices)
{
InitializeFields();
_loginServices = loginServices;
_dialogService = dialogServices;
DomainList = _loginServices.GetDomainListing();
}
I have mocked the dependencies as follows:
Mock<ILoginServices> moq = new Mock<ILoginServices>();
moq.Setup(log =>
log.LoginUser(It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<string>()))
.Callback<string, string, string>((i, j, k) => CheckArgs(i, j, k));
moq.Setup(log2 =>
log2.GetDomainListing()).Returns(new List<string> { "Domain" });
Mock<IDialogService> moq2 = new Mock<IDialogService>();
I have also tried inserting real services as the parameters.
I have verified that the mocks do work, and the objects these mocks
return are not null.
I have commented out all the code in the constructor.
I have tried inserting the line
LoginViewModel test = new LoginViewModel(_fakeLoginService,_fakeDialogService);
in front of the call to the constructor (to see if it had to do with the original local variable being disposed or something before) and this line crashed instead.
From all I can see this must be the constructor,(but not the code I have written inside it) and that this is solely related to NUnit / Moq as my code still compiles and runs fine.
I have no idea on this one guys, can anyone point me in the right direction?
[Edit]
Ok so I have run through the code and the error comes from this line of code:
ImageSource = (ImageSource)Application.Current.FindResource(_imageName);
This code is going to a ImageDictionary and getting a reference to the image for an undo button in the WindowViewModel (which my LoginViewModel inherits).
My hypotheses as to why its working in the normal running of the application, but not in the testing are:
1) Because I am running the program code through NUnit, the Application.Current object isnt getting property assigned/there is no Application.Current object to get.
**or**
2) Something to do with the fact that because the program code is being run in NUnit, the code doesn't have access to/can't resolve the ImageDictionary to find the image.
I'm leaning more strongly to the first hypothesis, but I'm as of yet not 100% sure, and I am having trouble finding the values of the Application.Current at runtime, cause when I move my cursor over the code the tooltip that normally appears showing the detail of the object that is not appearing.
My new question is: Does any of this make sense? Do you guys know if the Application.Current object exists / can be accessed when running the testing project through NUnit?
Any help will be appreciated.
You are correct. Application.Current is null for Unit tests. You can work around this by injecting the Application object as referencing singletons in code can make life tricky.

Adding state to bean generated via CGLIB's BeanGenerator

I see the following example code on how a Java Bean can be created dynamically. What I am not able to figure out is how I can update the state of an instance once created.
So in the following example how can I set the value of foo to "footest" for instance bean?
BeanGenerator bg = new BeanGenerator();
bg.addProperty("foo", Double.TYPE);
bg.addProperty("bar", String.class);
Object bean = bg.create();
Thanks
Kumar
A few ways come to mind:
1/ Call "setFoo()" on "bean" using reflection. Not pretty.
2/ Use a helper library to do the same thing - e.g. Commons-Beanutils o.a.c.BeanUtils.PropertyUtils.setProperty(bean, "foo", "footest").
This way works nicely for me. You could use the Spring equivalent if you're already using Spring.
3/ Use CGLIB's BeanMap upon your new bean. e.g.
Map beanMap = BeanMap.create(bean);
beanMap.put("foo", "footest");

JUnit Easymock Unexpected method call

I'm trying to setup a test in JUnit w/ EasyMock and I'm running into a small issue that I can't seem to wrap my head around. I was hoping someone here could help.
Here is a simplified version of the method I'm trying to test:
public void myMethod() {
//(...)
Obj myObj = this.service.getObj(param);
if (myObj.getExtId() != null) {
OtherObj otherObj = new OtherObj();
otherObj.setId(myObj.getExtId());
this.dao.insert(otherObj);
}
//(...)
}
Ok so using EasyMock I've mocked the service.getObj(myObj) call and that works fine.
My problem comes when JUnit hits the dao.insert(otherObj) call. EasyMock throws a *Unexpected Method Call* on it.
I wouldn't mind mocking that dao in my test and using expectLastCall().once(); on it, but that assumes that I have a handle on the "otherObj" that's passed as a parameter at insert time...
Which of course I don't since it's conditionally created within the context of the method being tested.
Anyone has ever had to deal with that and somehow solved it?
Thanks.
You could also use EasyMock.isA(OtherObj.class) for a little more type safety.
If you can't get a reference to the object itself in your test code, you could use EasyMock.anyObject() as the expected argument to yourinsert method. As the name suggests, it will expect the method to be called with.. well, any object :)
It's maybe a little less rigorous than matching the exact argument, but if you're happy with it, give it a spin. Remember to include the cast to OtherObjwhen declaring the expected method call.
The anyObject() matcher works great if you just want to get past this call, but if you actually want to validate the constructed object is what you thought it was going to be, you can use a Capture. It would look something like:
Capture<OtherObj> capturedOtherObj = new Capture<OtherObj>();
mockDao.insert(capture(capturedOtherObj));
replay(mockDao);
objUnderTest.myMethod();
assertThat("captured what you expected", capturedOtherObj.getValue().getId(),
equalTo(expectedId));
Also, PowerMock has the ability to expect an object to be constructed, so you could look into that if you wanted.
Note also that if you use EasyMock.createStrictMock();, the order of the method calls is also important and if you break this rule, it would throw an unexpected method call.