嘲讽不工作的插座
问题描述:
类
我想回到每当新的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"
有人可以请帮助?
答
您的类路径中没有必要的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
}
}
上午用TestNG中,当我把unWith(PowerMockRunner.class) – user3155754
永远不要说“这是给我一个错误”,它给我的错误。始终说出实际的错误。我猜这是由于缺少JAR而导致的另一个类未发现的错误。 – slim
我的下线是@RunWith(PowerMockRunner.class)仅适用于JUNIT,需要知道它是否也适用于TESTNG? – user3155754