jeudi 26 mars 2015

PowerMock mockStatic didn't catch mocked static void method call

I try to mock a static void method with PowerMock over Mockito, but it doesn't work so well.


My sample code:


BlackTempleTest.java



package com;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import com.BlackTempleTest.Illidan;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Illidan.class, EvilBrother.class })
public class BlackTempleTest {

Answer<Object> defaultAnswer = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
System.out.println("Haha!");
return null;
}
};

@Test(expected = AssertionError.class)
public void testIllidanFight() throws Exception {
Illidan.startFight();
}

@Test
public void testCheatOnIllidanFight() throws Exception {
PowerMockito.mockStatic(Illidan.class, defaultAnswer);

Illidan.startFight();
}

@Test(expected = AssertionError.class)
public void testEvilBrotherFight() throws Exception {
EvilBrother.startFight();
}

// dont work
@Test
public void testCheatOnEvilBrotherFight() throws Exception {
PowerMockito.mockStatic(EvilBrother.class, defaultAnswer);

EvilBrother.startFight();
}

static class Illidan {
static void startFight() {
Assert.fail("You are not prepared!");
}
}
}


EvilBrother.java



package com;

import com.BlackTempleTest.Illidan;

public class EvilBrother extends Illidan {

}


My problem is, that the nested class is mocked as expected with a combination of @PrepareForTest and PowerMockito.mockStatic, but if the class is in its own class file, these statements don't work.


How can a fix this test?


Aucun commentaire:

Enregistrer un commentaire