Verify Spock mock with specified timeout

前端 未结 4 450
灰色年华
灰色年华 2021-01-04 21:20

In Mockito there is option to verify if mock method has been called, and specify timeout for this verification (VerificationWithTimeout), for example:



        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-04 22:12

    This doesn't do exactly what the question asked, but I found it a bit cleaner that using a variable. If you have other conditions to asynchronously test in addition to the interaction, then you can declare the interactions at mock creation time and then use PollingConditions to test the other conditions. PollingConditions will either fail the test or block until the conditions pass, so that by the time the interaction is tested, the method should have been called:

    @MicronautTest
    class KernelManagerTest extends Specification {
    
        @Inject
        KernelManager kernelManager
    
        //create conditions
        PollingConditions conditions = new PollingConditions(timeout: 10, initialDelay: 1)
    
        class Exits {
    
            static createKernel (String[] args) {
                System.exit(args[0].toInteger())
            }
    
        }
    
        def "handles a system exit from within kernel"() {
            given:
            // set custom kernel
            kernelManager.kernelClass = Exits
            // create custom logger
            kernelManager.log = Mock(Logger) {
                1 * warn("Kernel exited unexpectedly.", _ as UnexpectedExitException)
            }
    
            when:
            // create new kernel (exit 1)
            kernelManager.startNewKernel("1")
    
            then:
            conditions.eventually {
                kernelManager.kernelInstances.size() == 0
                kernelManager.kernelThreads.size() == 0
            }
        }
    }
    
    
    

提交回复
热议问题