单个测试课程的模拟制造商



我有一个带有许多测试文件的项目。在其中一个测试课程中,我需要模拟Finall课程。正如我发现的那样,可以使用Mockmaker(链接)来完成,但是这打破了我所有的其他测试课程作为原因:

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);

没有模拟制造商的所有其他测试都很好。

如何仅在单个测试类上指定仅使用Mockmaker?

尝试使用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使用。

您无法基于此链接模拟最终类:https://github.com/mockito/mockito/mockito/wiki/faq#what-what-are-are-are-are-the-limitations-of-mockito-mockito

请参阅以下链接:

如何用Mockito嘲笑最后一堂课

如何用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);
    }
}

示例链接:https://dzone.com/articles/mock-final-class

相关内容

  • 没有找到相关文章

最新更新