Как смоделировать UUID в Spock + PowerMock? - PullRequest
0 голосов
/ 11 марта 2019

Если я хочу использовать статический метод, мне нужно использовать PowerMock.Я хорошо протестировал в PowerMock + JUnit, но потерпел неудачу в сочетании со Споком.

Encry.java

public class Encrypt {
    public String genUUID() {
        return UUID.randomUUID().toString();
    }
}

EncryptTest2Java.java работает:

@PrepareForTest({ UUID.class, Encrypt.class })
@RunWith(PowerMockRunner.class)
public class EncryptTest2Java {
    @Test
    public void genUUID() {
        final String id = "493410b3-dd0b-4b78-97bf-289f50f6e74f";
        UUID uuid = UUID.fromString(id);
        PowerMockito.mockStatic(UUID.class);
        PowerMockito.when(UUID.randomUUID()).thenReturn(uuid);
        Encrypt encrypt = new Encrypt();
        Assert.assertEquals(id, encrypt.genUUID());
    }
}

Но в Споке это не работает:

EncryptTest.groovy

@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(Sputnik.class)
@PrepareForTest([UUID.class, Encrypt.class])
class EncryptTest extends Specification {
    def "PasswordGenerator"() {
        given:
        final String id = "493410b3-dd0b-4b78-97bf-289f50f6e74f";
        UUID uuid = UUID.fromString(id)

        PowerMockito.mockStatic(UUID.class)
        PowerMockito.when(UUID.randomUUID()).thenReturn(uuid)
        Encrypt encrypt = new Encrypt()

        when:
        String ret = encrypt.genUUID()

        then:
        ret == id
    }
}

Информация об ошибке:

Notifications are not supported for behaviour ALL_TESTINSTANCES_ARE_CREATED_FIRST
Notifications are not supported for behaviour ALL_TESTINSTANCES_ARE_CREATED_FIRST
Notifications are not supported when all test-instances are created first!
Notifications are not supported for behaviour ALL_TESTINSTANCES_ARE_CREATED_FIRST
Notifications are not supported for behaviour ALL_TESTINSTANCES_ARE_CREATED_FIRST
Notifications are not supported for behaviour ALL_TESTINSTANCES_ARE_CREATED_FIRST
Notifications are not supported for behaviour ALL_TESTINSTANCES_ARE_CREATED_FIRST

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.


    at arthur.dy.lee.mybatisplusdemo.EncryptTest.PasswordGenerator(EncryptTest.groovy:24)


Process finished with exit code -1

Что мне делать?Не могли бы вы помочь мне?Спасибо!

...