Spring控制器测试模拟

时间:2015-05-29 15:41:00

标签: spring unit-testing testing controller

所以我有一些问题需要一个测试解决方案。

这是我想测试的方法(我对此很新)。它会在每次加载时清除网页上的所有字段。

@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));
}

由于这是我第一次做这种事情,我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

然后你必须做的只是断言值,例如:

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

如果您想确保是这种情况,可以这样做:

assertNotNull(mockSession.getAttribute("firstname"));
在发出GET请求之前