Is it possible to mock static final field (eg. System.out)

4,673 views
Skip to first unread message

sardine

unread,
Sep 17, 2009, 4:29:47 AM9/17/09
to PowerMock
I cann't find any discussion about mocking "static final field", any
suggestions? Is it possible to mock static final field using
PowerMock?

Code snippets for reference:

PowerMockito.mockStatic(System.class);

// How to mock static final field? Way 1:
System.out = Mockito.mock(PrintStream.class); // Compile Error: The
final field System.out cannot be assigned

// Way 2:
PrintStream out = Mockito.mock(PrintStream.class);
when(System.out).thenReturn(out); // Runtime Error: when() requires an
argument which has to be a method call on a mock

System.out.println("Hello");
verify(System.out).println("Hello");

Thanks in advance.

Johan Haleby

unread,
Sep 17, 2009, 6:47:47 AM9/17/09
to powe...@googlegroups.com
What do you mean by mocking static fields? Do you mean static methods?

You can indeed mock static methods in PowerMock, see http://code.google.com/p/powermock/wiki/MockStatic. How ever if you want to mock a static method in a system class (such as java.lang.System) you need to use this approach: http://code.google.com/p/powermock/wiki/MockSystem.

The latter doesn't work in PowerMock 1.2.5 for the Mockito extension though. Version 1.3 (not released yet) supports it so if you need this functionallity right now you should checkout and build PowerMock from trunk (using mvn install).

/Johan

sardine

unread,
Sep 17, 2009, 8:17:38 AM9/17/09
to PowerMock
I means that how to setup fixture, so that System.out will return
mocked one?

On Sep 17, 6:47 pm, Johan Haleby <johan.hal...@gmail.com> wrote:
> What do you mean by mocking static fields? Do you mean static methods?
>
> You can indeed mock static methods in PowerMock, seehttp://code.google.com/p/powermock/wiki/MockStatic. How ever if you want to
> mock a static method in a system class (such as java.lang.System) you need
> to use this approach:http://code.google.com/p/powermock/wiki/MockSystem.
>
> The latter doesn't work in PowerMock 1.2.5 for the Mockito extension though.
> Version 1.3 (not released yet) supports it so if you need this
> functionallity right now you should checkout and build PowerMock from trunk
> (using mvn install).
>
> /Johan
>

Johan Haleby

unread,
Sep 17, 2009, 8:57:15 AM9/17/09
to powe...@googlegroups.com
As I said you cannot do it with the current Mockito extension API right now. With EasyMock extension API checkout http://code.google.com/p/powermock/source/browse/trunk/modules/module-test/powermock/junit4-test/src/test/java/samples/junit4/system/SystemClassUserTest.java.

In your particular case I'm not sure why you want to mock System.out, personally I would avoid doing it. You can modify the outputstream using System.setOut(..).

/Johan
Reply all
Reply to author
Forward
0 new messages