简体   繁体   English

如何在grails中的spock单元测试中测试方法调用和重定向的顺序?

[英]How to test order of method calls and redirects in spock unit testing in grails?

I've been seeing some weird behavior with grails controller methods which has had me wanting to create a test case to see if I can reproduce this consistently. 我一直在看grails控制器方法的一些奇怪行为,这让我想要创建一个测试用例,看看我是否可以一致地重现这个。 So,.. I'll explain the issue first to better understand my question. 所以,我将首先解释这个问题,以便更好地理解我的问题。

I've had some weird behavior recently that when a grails method is called, it sometimes doesn't finish all the method implementation (basically all code goes to server calls) and does the redirect too early. 我最近有一些奇怪的行为,当调用grails方法时,它有时无法完成所有方法实现(基本上所有代码都转到服务器调用)并且过早地重定向。 I can see this by my service methods still running but the ui has already (sometimes also incorrectly) redirected wrongly. 我可以通过我的服务方法仍然运行来看到这个,但是ui已经(有时也错误地)重定向错误。 I've tried debugging through it, but it also leads me to the same places,.. I'll be in a service method but see the page already rendering on the ui. 我已经尝试通过它调试,但它也引导我到相同的地方,..我将在一个服务方法,但看到已经在ui上呈现的页面。 If I could get a good test case going, I feel this may be easier to debug. 如果我能得到一个好的测试用例,我觉得这可能更容易调试。

Example controller code: 示例控制器代码:

def blam() {
   Foo foo = Foo.get(params.id)
   String msg = service.method1(foo)
   service.method2(foo)
   service.doSomething(foo)
   redirect(action:"list", controller: "blam", params: [msg:msg, *:params])
}

Example test code: The problem below is that it doesn't actually test a call order at all, I want to test that it is calling the methods in the right order. 示例测试代码:下面的问题是它根本没有实际测试一个调用顺序,我想测试它是否按正确的顺序调用方法。 I have found a couple examples say that you may call multiple then declarations but I dont see a difference if I move the methods around and re run the test. 我发现有几个例子说你可以调用多个声明,但是如果我移动方法并重新运行测试,我就不会看到差别。

def "test service call order and redirect"(){
   when:
   controller.actionMethod()

   then:
   service.method1(_) * 1
   service.method2(_) * 1
   service.doSomething(_) * 1

   then:
   response.redirectedUrl == "bam/list"   
}

Any help with how to test this scenario would be greatly appreciated! 任何有关如何测试此场景的帮助将不胜感激! Also I know it's not the main question but ideas on the redirect are also welcome! 另外我知道这不是主要问题,但欢迎重定向的想法! (or should I create a different question?) (或者我应该创建一个不同的问题?)

Cheers! 干杯!

Use multiple then blocks: 使用多个块then

then:
   service.method1(_) * 1

then:
   service.method2(_) * 1

then:
   service.doSomething(_) * 1

The order should be respected then (see http://spock-framework.readthedocs.org/en/latest/interaction_based_testing.html#invocation-order ) 该订单应该得到尊重(参见http://spock-framework.readthedocs.org/en/latest/interaction_based_testing.html#invocation-order

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM