我有一个包含许多测试文件的项目。在其中一个测试类中,我需要模拟finall类。正如我发现它可以用MockMaker(link)完成,但是这会打破我所有其他测试类showin的原因:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
没有Mock-Maker所有其他测试都没问题。
如何指定仅在单个测试类上使用MockMaker?
答案 0 :(得分:1)
尝试使用PowerMockito ..它可以很好地处理决赛和静电:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
嘲笑最后一堂课:
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({MyFinalClass.class})
public class MyTest {
@Test
public void myFinalClassTest() {
MyFinalClass finalMock= PowerMockito.mock(MyFinalClass .class);
Mockito.when(finalMock.toString()(testInput)).thenReturn("abc");
// Assertions
}
}
您只在需要的地方使用此功能..在所有其他地方,您可以保留原始的Mockito用途。
答案 1 :(得分:0)
您无法根据以下链接模拟最终课程:https://github.com/mockito/mockito/wiki/FAQ#what-are-the-limitations-of-mockito
请参阅以下链接:
How to mock a final class with mockito
How to mock a final class with mockito
尝试使用Power Mockito,如下所示:
public final class Plane {
public static final int ENGINE_ID_RIGHT = 2;
public static final int ENGINE_ID_LEFT = 1;
public boolean verifyAllSystems() {
throw new UnsupportedOperationException("Fail if not mocked!");
}
public void startEngine(int engineId) {
throw new UnsupportedOperationException(
"Fail if not mocked! [engineId=" + engineId + "]");
}
}
public class Pilot {
private Plane plane;
public Pilot(Plane plane) {
this.plane = plane;
}
public boolean readyForFlight() {
plane.startEngine(Plane.ENGINE_ID_LEFT);
plane.startEngine(Plane.ENGINE_ID_RIGHT);
return plane.verifyAllSystems();
}
}
并测试最终课程:
@PrepareForTest(Plane.class)
public class PilotTest extends PowerMockTestCase {
@Test
public void testReadyForFlight() {
Plane planeMock = PowerMockito.mock(Plane.class);
Pilot pilot = new Pilot(planeMock);
Mockito.when(planeMock.verifyAllSystems()).thenReturn(true);
// testing method
boolean actualStatus = pilot.readyForFlight();
Assert.assertEquals(actualStatus, true);
Mockito.verify(planeMock).startEngine(Plane.ENGINE_ID_LEFT);
Mockito.verify(planeMock).startEngine(Plane.ENGINE_ID_RIGHT);
}
}