我正在尝试在服务单元测试中使用Grails Fixtures Plugin 。我正在使用 grails 2.2。
我的 BuildConfig.groovy 中有下一个代码
plugins {
compile ":fixtures:1.2"
compile ":build-test-data:2.0.3"
...
..
.
}
最初我尝试过
@TestFor(HotelService)
@Mock([Place])
class HotelServiceTests {
def fixtureLoader
void testFixturesInUnitTests() {
def fixture = fixtureLoader.build {
hotel(Place, name: "Hotel Hilton")
}
}
}
上述测试失败:
| java.lang.NullPointerException: Cannot invoke method build() on null object
通过 Google 搜索,我在Grails 用户邮件列表中发现,fixtureLoader 必须在单元测试中显式创建。
import grails.plugin.fixtures.*
@TestFor(HotelService)
@Mock([Place])
class HotelServiceTests {
def fixtureLoader
def grailsApplication
@Before
void setUp() {
fixtureLoader = new FixtureLoader(grailsApplication)
}
void testFixturesInUnitTests() {
def fixture = fixtureLoader.build {
hotel(Place, name: "Hotel Hilton")
}
}
}
测试失败,出现下一个错误:
java.lang.NullPointerException: Cannot invoke method hasGrailsPlugin() on null object
at grails.plugin.fixtures.builder.FixtureBuilder.lookForBuildTestDataPlugin(FixtureBuilder.groovy:53)
at grails.plugin.fixtures.builder.FixtureBuilder.<init>(FixtureBuilder.groovy:49)
at grails.plugin.fixtures.Fixture.createBuilder(Fixture.groovy:75)
at grails.plugin.fixtures.Fixture.build(Fixture.groovy:44)
at grails.plugin.fixtures.FixtureLoader.build(FixtureLoader.groovy:46)
另一个谷歌搜索,我发现了一个“黑客”来避免以前的错误。
import grails.plugin.fixtures.*
import org.codehaus.groovy.grails.plugins.GrailsPluginManager
import org.codehaus.groovy.grails.plugins.PluginManagerHolder
@TestFor(HotelService)
@Mock([Place])
class HotelServiceTests {
def fixtureLoader
def grailsApplication
@Before
void setUp() {
fixtureLoader = new FixtureLoader(grailsApplication)
PluginManagerHolder.pluginManager = [hasGrailsPlugin: { String name -> true }] as GrailsPluginManager
}
void testFixturesInUnitTests() {
def fixture = fixtureLoader.build {
hotel(Place, name: "Hotel Hilton")
}
}
}
现在我收到下一个错误:
java.lang.NullPointerException: Cannot invoke method isDomainClass() on null object
at grails.plugin.fixtures.buildtestdata.BuildTestDataBeanDefinitionTranslator.translate(BuildTestDataBeanDefinitionTranslator.groovy:54)
at grails.plugin.fixtures.buildtestdata.BuildTestDataBeanDefinitionTranslator.translate(BuildTestDataBeanDefinitionTranslator.groovy:43)
at grails.plugin.fixtures.builder.FixtureBuilder.translateToBuild(FixtureBuilder.groovy:126)
at grails.plugin.fixtures.builder.FixtureBuilder.invokeMethod(FixtureBuilder.groovy:121)
at com.softamo.movilrural.TopRuralScraperServiceTests$_testFixturesInUnitTests_closure2.doCall(TopRuralScraperServiceTests.groovy:26)
我不知道如何解决这个问题。任何反馈都非常受欢迎。