我有一个基于web的应用程序,每次在后端执行某些操作时,都会从服务器向客户端发送消息。现在,我正在编写一些测试,看看发送给客户端的消息是否是预期的消息。每个动作在执行时都会产生一条特定的消息,该消息被发送到客户端。在我的测试中,我创建了一个WebSocket客户机来侦听服务器。现在,当我执行某些操作时,我应该检查是否正在发送该操作的预期消息。请注意,服务器需要一些时间来发送消息。
以下只是伪代码:
class ApplicationTest
public void checkIfEventCreatedMsgIsSent() {
Application.createNewEvent("Id101");
// Wait till the application sends message to the client
// And then check that the message sent is the correct one
// if (expectedMessage == recievedMessageFromClient) {
// success();
// }
}
class Client
public void readMessage(Message message) {
// Received the new event message with Id101
// Now this message should be sent to ApplicationTest.checkIfEventCreatedMsgIsSent and confirmed by it
}
}我把信息传达给客户,一切都很好。
但是,我想不出如何通知ApplicationTest客户端已经接收到消息,然后进行验证。我尝试在这里实现Observer Design Pattern,但这使我更加困惑。我应该如何实现这一点,以及哪种设计模式最适合这样的场景?
发布于 2014-03-20 18:59:16
用一些基本的假设重写你的课程
我们正在存储一个像Map<String, Object> msg = new HashMap<String, Object>()这样的值映射,它将与(EventId, EventDetailsObject).一起加载,上面的Map将存储在ServletContext中,它可以是MQ上的持久消息,也可以是db中的一个值。客户端没有发送任何确认,但是ApplicationTest轮询来查找事件是否创建,试图不详细地了解其他实现细节,让我知道这是否对您有意义?
class ApplicationTest
public void checkIfEventCreatedMsgIsSent() {
Application.createNewEvent("Id101");
// Wait till the application sends message to the client
// And then check that the message sent is the correct one
// if (expectedMessage == recievedMessageFromClient) {
// success();
// }
int iCount = 0;
int final MAXCOUNT = 5;
// Assuming client doesnt send an acknowledgement
// but Server pools to find that
// Below is Polling code method to check if event is created
// Servlet context is an example
// it could be a persistent message on MQ or a value in db
while(iCount < 5) {
if (servletcontext.get(msg).get("Id101") == null) {
count++;
sleep(5000);
} else { System.out.println("Eureka, msg is sent!")}
}
}
class Client{
public void readMessage(Message message) {
// Received the new event message with Id101
// Now this message should be sent to
// ApplicationTest.checkIfEventCreatedMsgIsSent and confirmed by it
// Below msg is a singleton object in Servlet context as an example
// it could be a persistent message on MQ or a value in db
// Map<String, Object> msg = new HashMap<String, Object>();
synchronized(servletContext) {
servletcontext.get(msg).put("Id101", <object>);
}
}
}https://stackoverflow.com/questions/22540204
复制相似问题