2014-02-19 65 views
0

我想回到每當新的Socket(「服務器IP」,端口編號)被稱爲定義Socket實例, 我的代碼看起來像這樣(我使用了EasyMock)嘲諷不工作的插座

public static Socket mockSocket ; 
public static Object []arguments = {"Test Client",8443}; 
........................................... 
.............................................. 

mockSocket = new Socket("20.206.214.76", 8080); 

PowerMock.createMock(Socket.class, arguments);  

expectNew(Socket.class,arguments).andReturn(mockSocket); 

其給我的編譯錯誤 - >

PowerMock.createMock(Socket.class, arguments); 

錯誤是:

"The type org.easymock.ConstructorArgs cannot be resolved. It is indirectly referenced from required .class files" 

有人可以請幫助?

回答

0

您的類路徑中沒有必要的EasyMock罐。編譯器正在尋找類org.easymock.ConstructorArgs並找不到它。

然而,一旦你在你的類路徑中獲得了正確的jar包,你就需要對Java和嘲笑有一個大致的瞭解。

// here you create a *real* Socket and assign it to 'mockSocket' 
mockSocket = new Socket("20.206.214.76", 8080); 

// here you create a mock Socket, but don't assign it to anything 
// 'arguments' probably doesn't do what you expect. 
PowerMock.createMock(Socket.class, arguments); 

// here you tell your test case to intercept calls to `new Socket()` and 
// return mockSocket (which, as we see above) is a real socket. 
expectNew(Socket.class,arguments).andReturn(mockSocket); 

你真正需要做的是創建一個真正的插座。將您創建的模擬套接字分配給mockSocket,並將其用於expectNew。您的測試課程需要註明@PrepareForTest,否則expectNew()將不起作用。

@RunWith(PowerMockRunner.class) 
@PrepareForTest(MyClass.class) 
public class MyClassTest { 
    // ... 
    @Test 
    public void testSocket() { 
     // create mock object 
     Socket mockSocket = PowerMock.createMock(Socket.class); 
     // tell test runner to intercept 'new Socket()' 
     expectNew(Socket.class,arguments).andReturn(mockSocket); 

     MyClass objectUnderTest = new MyClass(); 
     // do things to objectUnderTest 
     // because of @PrepareForTest and expectNew(), when MyClass 
     // hits 'new Socket(...)' the mock will be returned instead. 
     // assert things about objectUnderTest 
    } 
} 
+0

上午用TestNG中,當我把unWith(PowerMockRunner.class) – user3155754

+0

永遠不要說「這是給我一個錯誤」,它給我的錯誤。始終說出實際的錯誤。我猜這是由於缺少JAR而導致的另一個類未發現的錯誤。 – slim

+0

我的下線是@RunWith(PowerMockRunner.class)僅適用於JUNIT,需要知道它是否也適用於TESTNG? – user3155754