2015-05-29 165 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