每当调用新的Socket(“server ip”,portNum)时,我想返回一个已定义的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 :(得分:0)
您的类路径中没有必要的EasyMock jar。编译器正在寻找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
}
}