0

I try to mock static method with mockito-inline in spock

given:
    try(MockedStatic<CryptoUtils> mockedStatic = Mockito.mockStatic(CryptoUtils.class)){
                mockedStatic.when({ -> CryptoUtils.decryptWithPrefixIV(any() as String, any() as String) }).thenReturn(word)
            }

But this doesnt work --- 'try' with resources is not supported in current version

Ayshan Rzayeva
  • 137
  • 2
  • 11

1 Answers1

2

You technically can put try with resources in spock test,

Groovy 3+ supports try..with..resources: ARM Try with resources

and spock pulls Groovy 3: See https://spockframework.org/

testCompile "org.spockframework:spock-core:2.0-groovy-3.0"

On the other hand, the mockStatic is active only to the moment when it is closed, which does not compose with Spock's blocks. Thus, usage of cleanup block may be preferred

Like a cleanup method, it is used to free any resources used by a feature method, and is run even if (a previous part of) the feature method has produced an exception. As a consequence, a cleanup block must be coded defensively; in the worst case, it must gracefully handle the situation where the first statement in a feature method has thrown an exception, and all local variables still have their default values.

class Test {
  static max(int a, int b) {
    return Math.max(a, b)
  }
}

def "testMockStatic"() {
  given:
  var mockedStatic = Mockito.mockStatic(Test.class)
  mockedStatic.when({ -> Test.max(2, 3) }).thenReturn(10)

  expect:
  Test.max(2, 3) == 10

  cleanup:
  mockedStatic?.close()
}

As cleanup block is executed even if exception is thrown, you may have a code that throws before mockStatic - in this case mockedStatic is null. Spock advises defensive coding for this case:

As a consequence, a cleanup block must be coded defensively; in the worst case, it must gracefully handle the situation where the first statement in a feature method has thrown an exception, and all local variables still have their default values.

Groovy’s safe dereference operator (foo?.bar()) simplifies writing defensive code.

Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • _"Spock pulls Groovy 3":_ While this is true for `2.0-groovy-3.0`, there is also a version `2.0-groovy-2.5`. Maybe the OP used that one or he simply used Spock 1.3. He did not specify. Great answer otherwise. – kriegaex Dec 31 '21 at 02:58
  • This was exactly the answer I was looking for in my upgrade to `2.2-M1-groovy-3.0`. I had tried to still use PowerMock for 1 test but the suggested alternative to Sputnik (JUnitRuntime) didn't work for me. Instead embraced the new Mockito power and this was the last piece to the puzzle. – Alex White Mar 17 '22 at 11:20