Grails:在单元测试中的applicationcontext中设置数据源bean

Grails: Setting datasource bean in applicationcontext in unit Tests

我正在使用 grails 3.2.7 & 我正在对具有以下代码行的方法进行单元测试:

void abc(){
ApplicationContext ctx = Holders.grailsApplication.mainContext
def dataSource = ctx.getBean('dataSource')
}

内部单元测试(JUnit)任何人都可以帮助我:How to set 'datasource' Bean in applicationContext?

我试过了:

applicationContext.beanFactory.registerSingleton("dataSource", DataSource)

但这行不通。 有人可以帮我吗?

所以,解决方案是:

Junit 测试内部 class:

Class TestCl {
    DataSource dataSource

      @Before
      public void setup() {
        defineBeans {
          def bb = new BeanBuilder()
          bb.beans {
            dataSource(BasicDataSource)
          }
        }
        applicationContext.beanFactory.registerSingleton("dataSource", dataSource)
       }
     }

我建议使用依赖注入来获取数据源 Bean,而不是通过应用程序上下文。

您可以执行以下操作:

Class SampleService {
   def dataSource

   def abc(){
     //do the thing with the dataSource!
   }
}

此外,我认为您需要集成测试而不是单元测试来实际测试持久性逻辑。 See this