我正在使用MFC进行单元测试。我的软件是SDI。
我有2个线程:第一个是图形线程,第二个是重现用户行为的单元测试过程。 当没有模态对话框时,它运行良好,我使用SendMessage(模拟点击按钮,或更改文本等)阻塞,直到消息被处理,所以我没有任何同步问题
但是当按钮打开Modal CDialog时,我无法使用SendMessage,因为只要打开模式对话框,单元测试线程就会被阻止。所以我使用PostMessage和Sleep。现在我的问题是得到当前打开的CDialog的指针。
以下是单元测试的代码
bool UnitTestBoite()
{
// Here I am in unit test thread
CFrameWnd *pMainFrame = (CFrameWnd *)AfxGetMainWnd();
// Post Message to notify the button ID_INSERER_BOITE is clicked
pMainFrame->PostMessageW(WM_COMMAND, MAKELONG(ID_INSERER_BOITE, 0), 0);
// In the handler of ID_INSERER_BOITE
// there is something like CDialog dlg(pMainFrame, IDD_BASE_BOITE); dlg.DoModal();
Sleep(1000);
UINT myModalTemplateId = IDD_BASE_BOITE;
...
要获得模态对话框指针,我试过:
CWnd* pChild = pMainFrame->GetWindow(GW_CHILD);
while (pChild != nullptr)
{
// Retrieve template ID
UINT nResourceId = GetWindowLong(pChild->GetSafeHwnd(), GWL_ID);
if (nResourceId == myModalTemplateId )
break;
pChild = pChild->GetWindow(GW_HWNDNEXT);
}
if (pChild == nullptr)
return false;
或
HWND hwndForeGround = ::GetForegroundWindow();
// Retrieve template ID
UINT nResourceId = GetWindowLong(hwndForeGround, GWL_ID);
if (nResourceId != myModalTemplateId )
return false;
或
CWnd *pModal = pMainFrame_->GetForegroundWindow();
// Retrieve template ID
UINT nResourceId = GetWindowLong(pModal->GetSafeHwnd(), GWL_ID);
if (nResourceId != myModalTemplateId )
return false;
这些代码段都没有奏效...... 我想到的最后一个解决方案是让我的所有CDialog类继承自定义类并注册所有打开的CDialog,但它有点侵入... 是否优雅"意味着这样做?
感谢阅读, 卢卡斯。