我有一个域类,它扩展了一个抽象类,它注入了spring security core plugin服务。如何模拟从Controller测试类中注入到域类中的服务?
class Extra extends WithOwner {
String name
}
abstract class WithOwner {
transient springSecurityService
User user
def getCurrentUser() {
return springSecurityService.currentUser
}
def beforeValidate() {
if(!user) {
user = getCurrentUser()
}
}
Boolean isLoggedUserTheOwner(){
return (user?.id == getCurrentUser()?.id)
}
}
我想实施控制器测试。
@TestFor(ExtraController)
@Mock([Extra, User, UserRole, Role])
class ExtraControllerTests {
void testEdit() {
def utils = new TestUtils()
def user1 = utils.saveUser1()
populateValidParams(params)
def extra = new Extra(params)
extra.user = user1
assert extra.save() != null
params.id = extra.id
def model = controller.edit() // Line 69
assert model.extraInstance == extra
}
}
如果我运行上面的测试中,我得到:
测试应用ExtraController.testEdit --unit --echoOut |运行1个单元测试... 1 of 1 - 从testEdit输出 - |失败:testEdit(com.softamo.movilrural.ExtraControllerTests) | java.lang.NullPointerException:在com.softamo.movilrural.WithOwner.getCurrentUser(WithOwner.groovy:8)上的空对象 上无法获取属性'currentUser'。com.softamo.movilrural.WithOwner.isLoggedUserTheOwner(WithOwner.groovy:18)上的 ) at com.softamo.movilrural.ExtraController.edit(ExtraController.groovy:39) at com.softamo.movilrural.ExtraControllerTests.testEdit(ExtraControllerTests.groovy:69) |完成1个单元测试,1未能在853ms
我曾尝试没有成功嘲笑这样的安全服务:
Extra.metaClass.springSecurityService = new MockSpringSecurityService(user1)
甚至嘲讽的方法
Extra.metaClass.getCurrentUser = { return user1 }
任何想法,我怎么可能解决这个问题。
您好!我陷入了同样的问题。你有没有为你的问题找出解决方案?或者,也许你有一个侧面注入一个域对象内的服务没有单元测试自动装配? – snowindy 2012-11-18 19:47:53
这个问题有什么好运?,面临同样的问题。 – 2015-11-01 06:27:29