2012-06-14 29 views
1

我有以下的Struts Action:單元測試Struts的

public ActionForward addSomething(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { 

    SomeForm sForm = (SomeForm) form;   
    Test t = testForm.toTest(); 

    if (tDao.checkExistsTest(t.getTest())) {    
     return mapping.findForward("failure");   
    } else { 
     t.setType(new TestType(tess)); 
     t.setPassword(testForm.getPassword()); 

     tDao.add(t); 

     return mapping.findForward("success"); 
    }   
} 

我做了以下代碼來測試testAddSomethingSuccess方法:

@Test 
public void testAddSomethingSuccess() throws Exception { 
    form.setTest("LOL"); 
    form.setTestName("lol"); 
    form.setPassword("12345"); 

    ActionForward forward = action.addSomething(mapping, form, request, response); 

    assertEquals(tDao.getList().get(0).getTest(), "LOL"); 
    assertEquals(tDao.getList().get(0).getTestName(), "lol"); 
    assertEquals(tDao.getList().get(0).getPassword(), "12345"); 

    assertEquals("success", forward.getName()); 
} 

我如何能實現testAddClientFailed()? ?? :

@Test 
public void testAddSomethingFailed() throws Exception { 
    form.setTestName("lol"); 
    t.checkIfExists("lol"); 


    ActionForward forward = action.addSomething(mapping, form, request, response); 

    assertEquals("failure", forward.getName()); 
} 

回答

0

您需要模擬tDaocheckExistsTest返回FALSE。

在你的類,它具有

public ActionForward addSomething(...) 

你應該注射方法(通過構造)或通過setter方法設置TDao的implentation這對於方法返回false例如

FakeDao implements TDao { 
public boolean checkExistsTest(...) {return false;} 
} 

或子類具體DAO並重寫此方法。

您也可以使用模擬框架來提供像JMockMockito這樣的實現。

+0

嗯,我做了你所說的,但我仍然無法進行測試。我不知道爲什麼:s – unnamed

+0

你需要告訴我們你做了什麼。 – blank

+0

我編輯我的問題添加:tDao.checkIfExists(「lol」); – unnamed

0

通過實現DAO,無論是具體還是通過模擬,返回falsecheckExistsTest,並檢查前進的名稱,你現在做的 - 還有什麼?

這是爲什麼依賴注入/控制反轉非常有用的原因之一。

不知道你是怎麼測試的,DAO是如何實例化的等等。很難提供具體的援助。最終(很顯然)要測試失敗,你必須失敗。