我找到了很好的SNMP服务器和SNMP客户端示例,但我不确定如何将JUnit测试实现到单个测试文件中:
public class SNMPClientTest
{
@Test
public void randomData()
{
SnmpTrap trap = new SnmpTrap("127.0.0.1",
"1.3.6.1.4.1.2789.2005.1={s}WWW Server Has Been Restarted",
2, "kschmidt", "MD5", "mysecretpass", "DES", "mypassphrase");
trap.doTrap();
}
}
public class SNMPServerTest
{
@Test
public void randomDatabaseData() throws SQLException, FileNotFoundException, IOException
{
V3TrapReceiver v3 = new V3TrapReceiver("127.0.0.1", "kschmidt", "MD5",
"mysecretpass", "DES", "mypassphrase");
v3.listen();
}
}
当我运行服务器时,我收到消息Waiting for traps..
,我无法继续JUnit测试。但我可以将它们分成两个单独的文件。
我怎么解决这个问题?您可以在此处找到完整的源代码:fistp
答案 0 :(得分:1)
如果您希望客户端和服务器在同一测试中运行,您可以考虑在单个测试中将它们作为单独的线程启动。
我通常会尽量避免这种情况,因为它确实为测试添加了一些复杂性和上下文管理。
请注意:
我没有为你的测试验证任何内容,所以这一切都是运行服务器,然后运行客户端而不期望输出或状态。
@Rule
public ErrorCollector collector = new ErrorCollector();
@Rule
public Timeout testTimeout = new Timeout(15, TimeUnit.SECONDS);
@Test
public void testServerClientCommunication throws Exception () {
final SnmpTrap trap = new SnmpTrap("127.0.0.1",
"1.3.6.1.4.1.2789.2005.1={s}WWW Server Has Been Restarted",
2, "kschmidt", "MD5", "mysecretpass", "DES", "mypassphrase");
final V3TrapReceiver v3 = new V3TrapReceiver("127.0.0.1", "kschmidt", "MD5",
"mysecretpass", "DES", "mypassphrase");
Runnable serverTask = new Runnable() {
@Override
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
v3.listen();
}
} catch (Throwable th) {
//Exceptions thrown outside of the main Junit execution won't get propagated back to fail the test
//Use the ErrorCollector to maintain awareness
collector.addError(th);
}
}};
//Create the Thread to handle the Server execution
final Thread serverExecutor = new Thread(serverTask, "SNMP Server");
/*
* Create the client task and thread.
*/
Runnable clientTask = new Runnable() {
@Override
public void run() {
try {
boolean clientIsDone = false;
while (!clientIsDone) {
trap.doTrap();
//FIXME: Determine the state that matters.
clientIsDone = true;
}
} catch (Throwable th) {
//Exceptions thrown outside of the main Junit execution won't get propagated back to fail the test
//Use the ErrorCollector to maintain awareness
collector.addError(th);
}
}};
Thread clientExecutor = new Thread(clientTask, "SNMP Client");
/*
* Start the server first
*/
//Don't hold the JVM if the server is not done.
serverExecutor.setDaemon(true);
serverExecutor.start();
/*
* Now start the client. Note that after the client traps successfully that it will interrupt the server thread.
* The intent is that the interrupt will allow the server thread to die gracefully
*/
clientExecutor.setDaemon(true);
clientExecutor.start();
//Since we off-threaded the tasks the test will consider itself 'done' unless we join with the client, which basically says
//"Hold the current thread at this point until the other thread completes."
clientExecutor.join();
}
答案 1 :(得分:0)
使用@BeforeClass注释的方法启动服务器。这将在调用任何其他测试之前运行。