tiebin-zhang / powermock

Automatically exported from code.google.com/p/powermock
Apache License 2.0
0 stars 0 forks source link

Mocking System.exit() doesn't call Answer #391

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Writing tests for command line java tool
2. Annotations @PrepareForTest and @RunWith used
3. Code in @Before:
PowerMockito.spy(System.class);
PowerMockito.doAnswer(new Answer<Void>() {

@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
                throw new SystemExitException(invocation.getArguments()[0]);
            }
        }).when(System.class);

What is the expected output? What do you see instead?
- Test ends with Exception instead of terminating the JVM.
- JVM isn't terminated but Exception isn't thrown either

What version of the product are you using? On what operating system?
Powermock 1.4.12 and Mockito 1.9.0 on Windows7 and Eclipse 3.7.2

Please provide any additional information below.
The system.exit() is mocked somehow but the answer isn't called

Original issue reported on code.google.com by Andreas....@googlemail.com on 8 Jun 2012 at 8:58

GoogleCodeExporter commented 9 years ago
I got it! 
I like Mockito instead od EasyMock because the record and replay is hidden in 
the framework. But the replay is triggered by the method call in when().
1. void methods are called by doAnswer().when(object).method()
2. non void static methods are called by doAnswer().when(class.method())

But my scenario of a static void method is a special case and not covered, so a 
manually triggered replay is needed. I inserted a System.exit(Mockito.anyInt()) 
after my above code and it worked. This is the nothing calling System.exit() I 
noticed before. Now the Exception is thrown.

I tried the .when(System.class, "exit", Mockito.anyInt()) but this calls the 
original System.exit().

My wish is the integration of this manual method call into PowerMockito somehow 
to eliminate this special behaviour of the api. Perhaps when(class) should 
return a proxy on which I can call static methods are the when(class, 
methodName, params) should behave like the manual call instead of invoking the 
method on the original class.

Original comment by Andreas....@googlemail.com on 10 Jun 2012 at 7:34

GoogleCodeExporter commented 9 years ago
You need to use real partial mocking (see Mocktio docs) or stub the method 
using the stubbing API. 

Original comment by johan.ha...@gmail.com on 13 Jul 2012 at 7:08