2017-02-15 247 views
3

我有一個包含很多測試文件的項目。在我需要嘲笑最後一堂課的其中一個測試課上。因爲我發現了它可以與MockMaker(link)來完成,然而,這打破了所有我的其他測試類舒的原因:單測試類模擬器

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其他所有測試都很好。

如何指定僅在單個測試類上使用MockMaker?

回答

1

嘗試使用PowerMockito ..它總決賽和靜態交易得好:

<dependency> 
    <groupId>org.powermock</groupId> 
    <artifactId>powermock-api-mockito</artifactId> 
    <version>1.6.5</version> 
    <scope>test</scope> 
</dependency> 

懲戒final類:

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用法。

+0

我不允許修改我的項目的POM,我也無法從「finall」改變類 –

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

嘗試使用電源的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