I have a switch statement to handle java enum foo, and I use spock to write some groovy unit tests. I already added a test that checks to see if each type of foo is processed without exception. Now I want to check that the unrecognized type foo will throw an exception.
To do this, I will have to mock the enumeration and have already seen the solution described here:
Mocking Java enum to add a value to check for a failed option
I also know that it is possible to do this with powermock, but I really like spock, as I find it incredibly easy and therefore looked for a solution using spock.
I thought something like this might work:
def "An unexpected type of foo causes an exception to be thrown"() {
given:
Foo foo = Mock()
when:
subjectUnderTest.handleFoo foo
then:
thrown Exception
}
However, this does not work with the following error message:
org.spockframework.mock.CannotCreateMockException: Cannot create mock for class com.Foo because Java mocks cannot mock final classes. If the code under test is written in Groovy, use a Groovy mock.
, -, , spock, .
. , , .
, , . , , , , .
, , , , . , , , , , () .
(, ) , , , , . , , , , - , , .
:
Enum Foo:
public enum Foo {
ONE, TWO;
}
foo:
private void handleFoo(Foo foo) {
switch (foo) {
case ONE:
doEventOne();
break;
case TWO:
doEventTwo()
break;
default:
throw new IllegalArgumentException("Do not know how to handle " + foo);
}