I'm working on a fresh Grails project and recently noticed the default convention in the Spring Security Core generated User class now auto-encodes the password via a beforeInsert/Update event. That's a nice, clean, DRY way of doing the encode, and also makes it impossible to forget to do so.
However, now when trying to write up some unit tests which make use of said User class, I find I either have to mock out the springSecurityService (due to the encode), or more preferably (and cleanly), I'd just override the beforeInsert/Update closure with one that does nothing. Typically in Groovy one can override a method using the ExpandoMetaClass, ala...
User.metaClass.beforeInsert = { /* do nothing */ }
...but I'm finding that the original beforeInsert continues to be called upon creating and saving a new User. This in turn causes my unit tests to blow up. It's trivial for me to just work around this and mock out the service, but the above should work. Am I missing something? Is there something different with GORM's event closures that I'm not picking up on?
In order to improve performance Grails uses reflection directly with caches method handles for invoking events and not Groovy's meta layer. The reason is that if you are saving hundreds of domain instances it can seriously hurt performance if Grails had to go through Groovy's meta layer for each event.
There are ways around this such as defining your own User class that disables the event based on a system/environment property that your test sets etc. but there is currently no way to override the methods via meta programming.
The beforeInsert closure actually is not only a method like toString() or save(), but also it is a pre-defined event supported by Gorm. Override the method will not prevent Gorm from firing the PreInsert event, which leads to the original process.
If necessary, you can replace the code in the beforeInsert with a private method and then override the private method
Related
I am running some tests in django but they depend on a response from an outside service. For instance,
I might create a customer and wish to acknowledge it has been created in the outside service.
Once I am done with testing I want to remove any test customers from the outside service.
Ideally, there would be a method similar to setUp() that runs after all tests have completed.
Does anything like this exist?
You can make use of either unittest.TestCase.tearDown or unittest.TestCase.tearDownClass
tearDown(...) is the method gets called immediately after the test method has been called and the result recorded.
but, the tearDownClass(...) is gets called after tests in an individual class have run. That is, once per test class.
IMO, using tearDownClass(...) method is more appropriate since you may not need to check/acknoledge the external service after search test cases of the same class
So Django's testing framework uses a Python standard library module, unittest. This is where the setUp() method comes from.
This library contains another method tearDown() that is called immediately after the tests are run. More info can be found here
I want to Unit Test the view model and for that I am Inheriting Mefbootstraper class so Please suggest the method to override the CreateShell method inside Bootstrapper which returns dummy dependency object.
Based on your last comment, you could avoid creating a Shell and the entire Bootstrapper. So, instead of calling Bootstrapper's run() method, you can create mocks for RegionManager, Comnposition Container and ResourceManager in order to pass them through ViewModel's constructor.
This would not be an issue as you would load these mock instances with the minimum information needed for the test.
Furthermore, real Bootstrapper would not be needed because its functionalities would not be targeted for testing.
I hope this helps, Regards.
I am learning unit testing and mocking. I have JUnit running, and instead of using a Mocking Framework, I have manually created mock classes by extending existing classes and interfaces. I would like to learn the mocking framework EasyMock because thats all thats available here at my work. While you might suggest some other mocking framework, they will not be available to me.
The Setup:
I have a View and a Presenter and a API backend. When the user clicks a button: "Check For Updates", the view calls the presenter.checkForUpdates() which does a call to api.checkForUpdates() and expects an callback. If the an exception occurs, the api will notify the presenter via a callback, and the controller will call the view method view.showUserError(). Callbacks are used not return parameters because of the async nature of hitting our API bac
kend.
The Object under test is the Presenter. Specifically, I want to test that the View.showUserError() gets called when an exception occurs in the Api. I believe I can mock Api.checkForUpdates() to immediately call the exception callback instead of doing an actual network call.
The problem is, I only see EasyMock mocking return values. For example:
EasyMock.expect(api.checkForUpdates()).andReturn(xxxx)
wont work for me, since api.checkForUpdates() does not return anything and instead does a callback. What I really want to do is something like:
EasyMock.expect(api.checkForUpdates()).andExecute(exceptionCallback(NetworkError));
But I don't see how to do that. Is there something that can do what I want or am I missing something basic?
Thanks
I think you can make a stub using ‘ Expect().andDelegateTo()’ API.
http://devlearnings.wordpress.com/2010/07/10/easymock-assert-arguments-of-method-call/
EasyMock is a good choice :-) Look at the documentation to get more information.
You can call do
andThrow(exceptionCallback(NetworkError) which might suit your needs.
If you need something more powerful, andAnswer will let you do anything you want to create the answer. andDelegateTo might also be a good choice but you will have to implement a class implementing the same interface as the mock. Which will probably be more complex than the two other options in your case.
I have some of WebClient Requests in my App and want to check the parsing of the retrieved data in a unit test. How Do I wait in the WP7 Silverlight UnitTestFramework for the event client_DownloadStringCompleted?
My approach to this has been to introduce a wrapper class around WebClient (well, I actually used HttpWebRequest in the end, as WebClient did too much in the UI thread...) implementing an interface. I could then create a FakeWebClient implementing IWebClient, allowing me to validate the URLs that were being fetched, and responding with errors, success cases etc as desired.
It's unfortunate that quite a few APIs in .NET aren't easily testable / fakable :(
Completely wrong approach here. You're unit testing the wrong thing.
What you want to do, is to move your parsing of the data out to another class, and define a interface, say:
interface IWebParser { MyResult Parse(string input); }
and then inject that into your class, and in your DownloadStringCompleted event, call iWebParser.Parse(e.Result).
Now you can test your implementations of the IWebParser. And replace it.
Unit Testing isn't meant to test implementation specific code. You might as well just use a accessor and test a private method then!
Usually you should not test with HTTP requests. But to write such tests anyway eventually this link will help you (asynchronous testing):
http://www.jeff.wilcox.name/2009/03/asynchronous-testing/
I have a security rule that a newly registered user has full permissions over their own user entity. I'm using Rhino.Security and the code works fine, but I want to create a unit test to make sure the appropriate call is made to setup the permission. Here is a simplified verison of the code:
public User Register(UserRegisterTask userRegistrationTask) {
User user = User.Create(userRegistrationTask);
this.userRepository.Save(user);
// Give this user permission to do operations on itself
this.permissionsBuilderService.Allow("Domain/User")
.For(user)
.On(user)
.DefaultLevel()
.Save();
return user;
}
I've mocked the userRepository and the permissionBuilderService but the fluent interface of the permissionBuilderService requires different objects to be returned from each method call in the chain (i.e. .Allow(...).For(...).On(...) etc). But I can't find a way to mock each of the objects in the chain.
Is there a way to test if the permissionBuilderService's Allow method is being called but ignoring the rest of the chain?
Thanks
Dan
I also ran into this and ended up wrapping the Rhino Security functionality in a service layer for two reasons:
It was making unit testing a real PITA and after spending a couple of hours hitting my head against a brick wall, this approach allowed me to mock this layer far more easily.
I started to feel that Rhino Security was being coupled very tightly to my controller (my application uses MVC). Wrapping the calls in another layer allowed me looser coupling to a specific security implementation and will allow me to easily swap it out with another - if I so choose - in the future.
Obviously, this is only one approach. But it made my life much easier...