【问题标题】:Why does naming the service "service" not work in integration tests?为什么将服务命名为“服务”在集成测试中不起作用?
【发布时间】:2016-11-24 07:24:34
【问题描述】:

我有一个如下所示的测试集成测试。

  package bibs

    import static org.junit.Assert.*
    import groovy.util.GroovyTestCase;

    import org.junit.*

    class BibsServiceTests extends GroovyTestCase{


        BibsService service

        @Before
        void setUp() {
            // Setup logic here

        }

        @After
        void tearDown() {
            // Tear down logic here


        }

        @Test
        void testSomething() {

            assertEquals service.convertRangeStringToRangeList("asd"), "asd"

        }
    }

当我运行集成测试时,我得到的错误是

 Running 1 integration test... 1 of 1
| Failure:  testSomething(bibs.BibsServiceTests)
|  java.lang.NullPointerException: Cannot invoke method convertRangeStringToRangeList() on null object
    at bibs.BibsServiceTests.testSomething(BibsServiceTests.groovy:30)
| Completed 1 integration test, 1 failed in 292ms
| Tests FAILED  - view reports in 

如果我将服务名称更改为服务以外的名称,例如

BibsService bibsService

然后测试通过。我想知道为什么会这样?谢谢!

【问题讨论】:

    标签: grails integration-testing


    【解决方案1】:

    我认为您对单元测试和集成测试有些混淆。

    在针对服务(例如 BibsService)编写单元测试时,您可以使用 @grails.test.mixin.TestFor 将服务注入到变量“service”下的测试中。

    例子:

    import grails.test.mixin.TestFor
    @TestFor(BibsService)
    BibsServiceSpec extends spock.lang.Specification {
      void "Test service exists"() {
        expect:
        null != service
      }
    }
    

    在编写集成测试时,Grails 使用弹簧注入使服务 bean 可用。这意味着在集成测试中使用它时需要服务 bean 的名称(例如 bibsService)。对于 Grails 服务,这通常是第一个小写字符,后跟名称的其余部分。

    例子

    BibsServiceSpec  extends spock.lang.Specification {
      // Injected via spring.
      BibsService bibsService
    
      ... Do test here ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-02
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多