Set static method several times using JMockit in JUnit test

I have a class with static methods that I am currently mocking at JMockit. Let's say it looks something like this:

public class Foo { public static FooValue getValue(Object something) { ... } public static enum FooValue { X, Y, Z, ...; } } 

I have another class (let it be called MyClass) that calls the static method Foo; I am trying to write test cases for this class. A JUnit test using JMockit looks something like this:

 public class MyClassTest extends TestCase { @NonStrict private final Foo mock = null; @Test public void testMyClass() { new Expectations() { { Foo.getValue((Object) any); result = Foo.FooValue.X; } }; } myClass.doSomething(); } 

This works fine and dandy, and when the test runs, my MyClass instance will correctly get the value of the Foo.FooValue.X enum when it calls Foo.getValue ().

Now I'm trying to iterate over all the values โ€‹โ€‹in an enumeration and re-run the test. If I put the above test code in a for loop and try to set the result of the outlined static method to each enum value, this will not work. The mocked version of Foo.getValue () always returns Foo.FooValue.X and will never be from other values โ€‹โ€‹when I iterate over the numbering.

How can I repeatedly mock a static method in a single JUnit test? I want to do something like this (but obviously this does not work):

 public class MyClassTest extends TestCase { @NonStrict private final Foo mock = null; @Test public void testMyClass() { for (final Foo.FooValue val : Foo.FooValue.values() { new Expectations() { { // Here, I'm attempting to redefine the mocked method during each iteration // of the loop. Apparently, that doesn't work. Foo.getValue((Object) any); result = val; } }; myClass.doSomething(); } } } 

Any ideas?

+6
java methods static junit jmockit
source share
1 answer

Instead of "mocking the method several times", you should write several consecutive return values โ€‹โ€‹in one record:

 public class MyClassTest extends TestCase { @Test public void testMyClass(@Mocked Foo anyFoo) { new Expectations() {{ Foo.getValue(any); result = Foo.FooValue.values(); }}; for (Foo.FooValue val : Foo.FooValue.values() { myClass.doSomething(); } } } 

You can also do this with Delegate if you need more flexibility.

+5
source share

All Articles