Home > database >  Hot to reset a method mock in Spock?
Hot to reset a method mock in Spock?

Time:11-11

I had a mocked bean in a configuration:

@Profile('test')
@Configuration
class TestSecurityConfig {
  private final mockFactory = new DetachedMockFactory()
  @Primary @Bean
  AuthUserDetailsProvider authUserDetailsProvider() {
      mockFactory.Stub(AuthUserDetailsProvider)
  }
}

By default, I mock a method call is setup() method for all tests.

def setup() {
    authProvider.authenticationPrincipal >> random(authUserDetails)
}

By in a specific test, I need to override the method mock

def 'exercise missed user processing'() {
    given: 'no user data'
    authProvider.authenticationPrincipal >> emptyUser
    ...
}

But it doesn't work. How can I override a method mocking in Spock? Is there any way to reset mock interceptions manually?

CodePudding user response:

But it doesn't work?

Whatever you put in setup will be executed before each test. If you don't want that, then the code probably shouldn't be in setup.

How can I override a method mocking in Spock?

If by "override" you mean undo what was done in setup and then do something else, I am not aware of a way to do that.

Is there any way to reset mock interceptions manually?

Not that I am aware of. It is unusual to tell the mock that you want a certain behavior and later tell the mock that you have changed your mind.

CodePudding user response:

Interactions defined in then blocks will have precedence over those defined in given/setup, for the preceding when block. Normally, you pare them with assertions, i.e., 1 * ... but it works for plain stubbing too.

import spock.lang.*

class ASpec extends Specification {
  List myList = Mock()
    
  def setup() {
    myList.get(0) >> 1
  }
    
  def "default behavior"() {
    expect: 
    myList.get(0) == 1
  }
    
  def "override behavior"() {
    when:
    def result = myList.get(0)

    then:
    myList.get(0) >> 42
    result == 42
  }
}

So in your case:

def 'exercise missed user processing'() {
    when:
    ...

    then:
    1 * authProvider.authenticationPrincipal >> emptyUser
    ...
}
  • Related