2015-05-29 225 views
1

所以我有一些問題提出了測試解決方案。彈簧控制器測試模擬

這是我想測試的方法(我是新手)。它會在每次加載時清除網頁上的所有字段。

@RequestMapping("/addaddressform") 
public String addAddressForm(HttpSession session) 
{ 
    session.removeAttribute("firstname"); 
    session.removeAttribute("surname"); 
    session.removeAttribute("phone"); 
    session.removeAttribute("workno"); 
    session.removeAttribute("homeno"); 
    session.removeAttribute("address"); 
    session.removeAttribute("email"); 

    return "simpleforms/addContact"; 
} 

和這裏是我迄今爲止的測試

package ControllerTests; 

import java.text.AttributedCharacterIterator.Attribute; 

import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.mock.web.MockHttpSession; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
import org.springframework.test.context.web.WebAppConfiguration; 
import org.springframework.test.web.servlet.MockMvc; 
import org.springframework.test.web.servlet.MvcResult; 
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; 
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; 
import org.springframework.test.web.servlet.result.MockMvcResultHandlers; 
import org.springframework.test.web.servlet.setup.MockMvcBuilders; 
import org.springframework.web.context.WebApplicationContext; 

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 


@RunWith(SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration (classes = {SimpleFormsControllerTest.class}) 

public class SimpleFormsControllerTest { 
    @Autowired 
    private WebApplicationContext wac; 
    private MockMvc mockMvc; 

    @Before 
    public void setup() { 
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 
    } 

    @Test 
    public void addAddressForm_ExistingContactDetailsInForm_RemovalFromSession()   throws  Exception{ 

    MockHttpSession mockSession = new MockHttpSession(); 

    mockSession.putValue("firstname", "test"); 
    mockSession.putValue("surname", "test"); 
    mockSession.putValue("phone", "test"); 
    mockSession.putValue("workno", "test"); 
    mockSession.putValue("homeno", "test"); 
    mockSession.putValue("address", "test"); 
    mockSession.putValue("email", "test"); 

    mockMvc.perform(get("simpleForms/addaddressform").session(mockSession)); 
} 

因爲這是我第一次過做這種事情我沒有太多的線索在哪裏去這個。

回答

0

然後,你必須做的僅僅是斷言值,例如:

assertNull(mockSession.getAttribute("firstname")); 

如果你想確保它的話,你可以這樣做:

assertNotNull(mockSession.getAttribute("firstname")); 

你解僱前GET請求。

+0

一旦我這樣做,測試失敗,因爲它仍然返回「測試」 – Tfish