How to mock springSecurityService in an unit test - unit-testing

I am unit testing a Grails controller method that internally creates an user instance. User domain class uses the springSecurityService of the Spring Security plugin to encode the password before inserting it into the database.
Is there a way to mock that springSecurityService from my unit test in order to get rid of that error?
Failure: Create new individual member(MemberControllerSpec)
| java.lang.NullPointerException: Cannot invoke method encodePassword() on null object
Please find my unit test below.
#TestMixin(HibernateTestMixin)
#TestFor(MemberController)
#Domain([User, IndividualPerson])
class MemberControllerSpec extends Specification {
void "Create new individual member"() {
given:
UserDetailsService userDetailsService = Mock(UserDetailsService)
controller.userDetailsService = userDetailsService
def command = new IndividualPersonCommand()
command.username = 'scott#tiger.org'
command.password = 'What ever'
command.firstname = 'Scott'
command.lastname = 'Tiger'
command.dob = new Date()
command.email = command.username
command.phone = '89348'
command.street = 'A Street'
command.housenumber = '2'
command.postcode = '8888'
command.city = 'A City'
when:
request.method = 'POST'
controller.updateIndividualInstance(command)
then:
view == 'createInstance'
and:
1 * userDetailsService.loadUserByUsername(command.username) >> null
and:
IndividualPerson.count() == 1
and:
User.count() == 1
cleanup:
IndividualPerson.findAll()*.delete()
User.findAll()*.delete()
}
}

One way to mock a service is to use Groovy's MetaClass
import grails.test.mixin.Mock
import grails.plugin.springsecurity.SpringSecurityService
...
#Mock(SpringSecurityService)
class MemberControllerSpec extends Specification {
def setupSpec() {
SpringSecurityService.metaClass.encodePassword = { password -> password }
}
def cleanupSpec() {
SpringSecurityService.metaClass = null
}
....
In this example, the call to SpringSecurityService.encodePassword() will simply return the password in plain text.
An approach using Mocks is discussed here.

You can to use this code to encode password in User:
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService?.passwordEncoder ? springSecurityService.encodePassword(password) : password
}
When springSecurityService is null, encodePassword is not called and NPE is not raised

When you use controller unit test with spring security rest plugin in Grails v4/v3, if your controller method reference springSecurityService methods like 'athenticatedUser', there will be NullPointException, because springSecurityService is not autowired into the spring application context.
Add code like below, you can inject springSecurityService and mock it's methods.
class GuessControllerSpec extends Specification implements ControllerUnitTest<GuessController> {
#Override
Closure doWithSpring() {
return {
// mock method
SpringSecurityService.metaClass.getCurrentUser = {return new User()}
// inject into spring context
springSecurityService(SpringSecurityService)
}
}
...
}

Related

Grails 3 Controller Unit Testing: Domain class validation not working in a ControllerUnitTest

I'm upgrading an inherited Grails 2 app to 3.3.10. We have controller methods that rely on Domain class validation to control logic flow, but we can't get DomainClass validation to work in ControllerUnitTests when running in Grails 3
For example,
Gift and RecipientAddress are DomainClasses and RecipientAddress.hasErrors() is used to validate against the RecipientAddress constraints.
def confirmAddress() {
Gift gift = Gift.get(params.giftId)
if (!gift) {
render(view: "index", model: [invalid: true])
return
}
recipientAddress = recipientAddressService.storeAddressInformation(params, gift)
if (recipientAddress.hasErrors()) {
render(view: "index", model: getAddressErrorModel(gift, recipientAddress))
return;
} else {
return [
recipientAddress : recipientAddress,
gift : gift
]
}
}
In the following test, when I debug the controller method it does everything expected but recipientAddress.hasErrors() always returns true and the test fails.
ie:
#Transactional
class GiftDetailsControllerTest extends Specification implements ControllerUnitTest<GiftDetailsController> {
#Shared
#AutoCleanup
SimpleMapDatastore dataStore = new SimpleMapDatastore([ConnectionSource.DEFAULT, "reporting"],
RecipientAddress, Gift)
def setup() {
controller.recipientAddressService = Mock(RecipientAddressService)
}
void "test RecipientAddress Bad PhoneNumber"() {
given:
RecipientAddress recipientAddress = new RecipientAddress(
phone: '123-456-789'
)
UnitTestDataFactory dataFactory = UnitTestDataFactory.getDataFactory()
Gift gift = dataFactory.getMockGift()
gift.save()
params.giftId = gift.id
when:
recipientAddress.validate()
controller.confirmAddress()
then:
recipientAddress.hasErrors()
recipientAddress.getErrors().getFieldError('phone')
1 * controller.recipientAddressService.storeAddressInformation(params, gift) >> recipientAddress
view == '/giftDetails/index'
}
}
Implementing DataTest ie: ...implements ControllerUnitTest<GiftDetailsController>, DataTest { fixes the DomainClass validation, but breaks the controllers ability to get the saved Gift.
Is there a way get DomainClass validation working in a ControllerUnit test?
Fix
Implemented DataTest with mockDomains and had to remove the custom dataStore.
#Transactional
class GiftDetailsControllerTest extends Specification implements ControllerUnitTest<GiftDetailsController>, DataTest {
// #Shared
// #AutoCleanup
// SimpleMapDatastore dataStore = new SimpleMapDatastore([ConnectionSource.DEFAULT, "reporting"], RecipientAddress, Gift)
void setupSpec() {
mockDomains RecipientAddress, Gift
}
....
Is there a way get DomainClass validation working in a ControllerUnit
test?
Yes.
You probably want something like this...
class GiftDetailsControllerTest extends Specification implements ControllerUnitTest<GiftDetailsController>, DataTest {
Class[] getDomainClassesToMock() {
[Gift]
}
// ...
}

How to mock passwordEncoder using Spock in a Grails unit test

I could use some advice in how to mock an auto wired dependency used in a Grails unit test. I've omitted most of the unnecessary code and just given the test class and the relevant methods in the file class under test
class UserService {
def springSecurityService // spring bean
def passwordEncoder // auto wired as per
//https://stackoverflow.com/questions/33303585/spring-//security-encode-password-with- bcrypt-algorithm
.....
def passwordPreviouslyUsed(String newPassword, def userId){
def passwordExists = false
def usersPasswords = findPasswordsForUser(userId)
usersPasswords.each{ password ->
if (passwordEncoder.isPasswordValid(oldPassword, newPassword, null)) {
passwordExists = true
}
}
return passwordExists
}
.....
def findPasswordsForUser(def userId){
User foundUser = User.findById(userId)
def passwordsForUser = UserPasswords.createCriteria().list {
eq('user', foundUser)
projections{
property('password')
}
}
passwordsForUser
}
My test
class UserServiceSpec extends Specification implements DataTest, ServiceUnitTest<UserService> {
def passwordEncoder
def setupSpec() {
mockDomains User, UserPasswords
}
def setup() {
def stubPasswordEncoder = Stub(passwordEncoder) {
isPasswordValid(_, _, _) >> true
}
service.passwordEncoder = stubPasswordEncoder
}
void "test for user passwordPreviouslyUsed"() {
given: "a user already exists"
setup()
service.createNewUser("testName", "testy#test.com", "Secret1234" )
//^(does some validation, then User.save())
User foundUser = User.findByEmail("testy#test.com")
foundUser.fullName == "testName"
long testUserId = foundUser.id
and: "we update the password for that user, and it to the userPasswords"
UserPasswords newUserPassword = new UserPasswords(
user: foundUser,
password: "newPassword1"
)
newUserPassword.save()
//use passwordPreviouslyUsed method to check a string with the same value as the
//previously
//updated password to check if it has already been used
when: "we check if the password has been used before"
def response = service.passwordPreviouslyUsed("newPassword1", fundsyId)
then:
response == true
}
Without stubbing or mocking this dependency, I get the error
Cannot invoke method isPasswordValid() on null object
I tried to stub password encoder and have it return true
def stubPasswordEncoder = Stub(passwordEncoder) {
isPasswordValid(_, _, _) >> true
}
service.passwordEncoder = stubPasswordEncoder
But this gives an error message:
Stub in 'spock.mock.MockingApi' cannot be applied to '(java.lang.Object, groovy.lang.Closure)'
Is there any way to mock this dependency with Spock?
Stub and Mock take a class - you're giving it an instance that is null - hence the exception.
You should be able to mock it as so:
def mockPasswordEncoder = Mock(PasswordEncoder)
// note this is the class
// org.springframework.security.crypto.password.PasswordEncoder
I tried enrichelgeson's approach, and it worked!
I first imported PasswordEncoder to the test class
import org.springframework.security.crypto.password.PasswordEncoder
then implemented the normal mocking procedure. I was initially confused because they class under test just implicitly created an instance of the class by defining it.
def stubPasswordEncoder = Stub(PasswordEncoder) {
isPasswordValid(_, _, _) >> true
}
service.passwordEncoder = stubPasswordEncoder
I also found another solution that didn't require mocking
service.passwordEncoder = [ isPasswordValid: { String rawPass, String salt, Null -> true } ]
Both approaches work fine. Thanks for the help!

how to avoid a domain call in unit testing with grails / spock

I have the following lines of code
username = username.stripIndent()
user = User."${databaseInstance}".findByUsername(username)
if (user == null){
return "User does not exist"
}
I'm trying to unit test this functionality with:
def setup() {
def mockUser = Mock(User)
myClass.user = mockUser
}
void "userNotFoundGetUserInfo"(){
given:
myClass.databaseInstance = 'X'
_ * mockUser._ >> null
when:
def result = myClass.getUserInfo(username)
then:
result == "User does not exist"
}
but I keep getting an error of "No such property: X for class mypackage.User"
I realize this is because i'm mocking the "user" object and not the "User" class, so how do I get around the fact that my code is making a direct call to a domain class?
Use Grails built-in #Mock annotation instead of Spock's Mock() method. Go like:
#Mock(User)
class YourTestSpecification extends Specification {
def setup() {
myClass.user = new User()
}
}
#Mock is meant to mock Grails domain classes.

How to use VndErrorJsonRenderer in grails unit test

I'm writing controller unit tests and I'd like to test json result when creation fails.
How can I register VndErrorJsonRenderer in unit test ? I tried simply defineBeans in setup() but it doesn't work :(
import com.vividsolutions.jts.geom.Coordinate
import grails.transaction.Transactional
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap
import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.NO_CONTENT
#Transactional(readOnly = true)
class UserController {
static namespace = "v1"
static allowedMethods = [profile: 'GET', create: "POST", update: "PUT", delete: "DELETE"]
static responseFormats = ['json', 'vnd.error+json']
def springSecurityService
def geometryFactory
/**
* Saves a resource
*/
#Transactional
def create() {
User instance = createResource(params)
instance.validate()
if (instance.hasErrors()) {
respond instance.errors, view: 'create' // STATUS CODE 422
return
}
instance.save flush: true
respond instance, [status: CREATED]
}
protected User createResource(GrailsParameterMap params) {
Double x = params.double("location.x", 0)
Double y = params.double("location.y", 0)
User user = new User()
bindData(user, params, [include: ['username', 'password', 'profile.*']])
if (x > 0 && y > 0)
user.location = geometryFactory.createPoint(new Coordinate(x, y))
else
user.location = null
user.roles = []
user.roles.add(Role.findByAuthority(Role.ROLE_USER))
return user
}
}
And my test :
#Before
void setup() {
defineBeans {
vndJsonErrorRenderer(VndErrorJsonRenderer)
}
}
void "Test the create action with a non unique username"() {
User.metaClass.encodePassword = {
"aaa"
}
// Create first user
assertNotNull getValidUser().save(flush: true)
when: "The create action is executed with a username already used"
def user = getValidUser()
controller.request.addHeader("Accept", "application/vnd.error+json,application/json")
controller.request.contentType = "application/json"
controller.request.content = JsonMapperUtil.mapAsJson(user)?.getBytes()
controller.create()
then: "The response status is UNPROCESSABLE_ENTITY and the username unique error is returned"
println response.text
response.status == UNPROCESSABLE_ENTITY.value
def json = JSON.parse(response.text)
assertNull "VND format not returned", json.errors
}
I'm using grails 2.3.6 with restful controller.
Thanks
In the case you are showing where you depend on respond it would be best to test this more as an integration test so all components that may interact with respond are all wired for you.
In a unit test for what ever beans are needed in the class under test I find it easiest to directly set them on the class under test.

JSON rendering fails for domain objects in ControllerUnitTestCase

I'm writing a unit test for a Grails controller that renders a domain class to a JSON response:
class MyController {
def find = {
def domainInst = MyDomainClass.get(params.id)
render ([data: domainInst] as JSON)
}
}
The unit test extends ControllerUnitTestCase and provides a mock for the domain object:
class MyControllerTests extends ControllerUnitTestCase {
#Before
void setUp() {
super.setUp()
mockDomain(MyDomainClass, [new MyDomainClass(id: 7)])
}
#Test
void testFind() {
def inst = MyDomainClass.get(7)
controller.params.id = inst.id
controller.find()
assert(controller.response.json.data.id == inst.id)
}
This all seems to be working nicely except for the JSON rendering, which spits out a nasty stack trace:
| Failure: testFind(MyControllerTests)
| org.apache.commons.lang.UnhandledException:
org.codehaus.groovy.grails.web.converters.exceptions.ConverterException: Error converting Bean with class MyDomainClass
Caused by: org.codehaus.groovy.grails.web.converters.exceptions.ConverterException: Error converting Bean with class MyDomainClass
at grails.converters.JSON.value(JSON.java:199)
at grails.converters.JSON.convertAnother(JSON.java:162)
at grails.converters.JSON.value(JSON.java:199)
at grails.converters.JSON.render(JSON.java:134)
... 5 more
Caused by: java.lang.reflect.InvocationTargetException
... 9 more
Caused by: groovy.lang.MissingMethodException: No signature of method: MyDomainClass.isAttached() is applicable for argument types: () values: []
Possible solutions: isAttached(), attach()
... 9 more
Changing the return to a Map instead of a domain class works:
render ([data: [id: domainInst.id]] as JSON)
What's causing the JSON marshaller to die on the domain class? It works in a normal environment, but not in the mock test environment. Is there a way to make this test work?
Looks like you might need to do some fine tuning to make the converters realize that you're trying to render a domain class as a JSON object. It works when you manually put your id into a map because it is rendering the response from a Map object instead of a Grails domain class, which needs to go through a special ObjectMarshaller.
Something like this:
// Domain Class
class Foo {
String foo
}
// Controller class
class MyController {
def find = {
def domainInst = Foo.get(params.id)
render domainInst as JSON
}
}
// Controller Test Class
class MyControllerTests extends ControllerUnitTestCase {
static application
#Before
void setUp() {
super.setUp()
// Register some common classes so that they can be converted to XML, JSON, etc.
def convertersInit = new ConvertersConfigurationInitializer()
convertersInit.initialize(application)
[ List, Set, Map, Errors ].each { addConverters(it) }
def xmlErrorMarshaller = new ValidationErrorsMarshaller()
XML.registerObjectMarshaller(xmlErrorMarshaller)
def jsonErrorMarshaller = new ValidationErrorsMarshaller()
JSON.registerObjectMarshaller(jsonErrorMarshaller)
ApplicationHolder.application.addArtefact("Domain", Foo)
mockDomain(Foo, [new Foo(foo: "foo")] )
}
#Test
void testJSON() {
def inst = Foo.list()[0]
controller.params.id = inst.id
def model = controller.find()
assert controller.response.json.foo == "foo"
}
#Override
protected def bindMockWebRequest(GrailsMockHttpServletRequest mockRequest, GrailsMockHttpServletResponse mockResponse) {
MockApplicationContext ctx = new MockApplicationContext()
application = new DefaultGrailsApplication([testClass] as Class[], getClass().classLoader)
application.initialise()
ctx.registerMockBean("grailsApplication", application)
ctx.registerMockBean(testClass.name, testClass.newInstance())
def lookup = new TagLibraryLookup(applicationContext: ctx, grailsApplication: application)
lookup.afterPropertiesSet()
ctx.registerMockBean("gspTagLibraryLookup", lookup)
ctx.registerMockBean(GroovyPagesUriService.BEAN_ID, new DefaultGroovyPagesUriService())
mockRequest.servletContext.setAttribute(ApplicationAttributes.APPLICATION_CONTEXT, ctx)
mockRequest.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx)
webRequest = new GrailsWebRequest(mockRequest, mockResponse, mockRequest.servletContext)
mockRequest.setAttribute(GrailsApplicationAttributes.WEB_REQUEST, webRequest)
RequestContextHolder.setRequestAttributes(webRequest)
}
}
Hope this helps!