【问题标题】:Spring Boot unittest with WebRequest with form submission included带有 Web 请求的 Spring Boot 单元测试,包括表单提交
【发布时间】:2017-05-08 02:15:38
【问题描述】:

我正在编写单元测试,但我偶然发现了一些我找不到适合我的需求或我已经拥有的代码的解决方案。

用户首先进入一个页面,他们必须(从下拉列表中)选择他们想要为其配置的品牌。在他们点击“提交”后,它会将他们带到一个页面,其中列出了每个类别的所有适当设置。

现在,品牌的选择是一个表单,提交给这个方法:

// Display a form to make a new Configuration
    @PostMapping("/addConfig")
    public String showConfigurationForm(WebRequest request, Model model) {
        // Get the ID of the selected brand
        Map<String, String[]> inputMap = request.getParameterMap();
        for (Entry<String, String[]> input : inputMap.entrySet()) {
            if (input.getValue().length > 0
                    && input.getKey().startsWith("brand")) {
                brandId = Integer.parseInt(input.getValue()[0]);
            }
        }
        // Load the view
        model.addAttribute("categoryResult",
                databaseService.getCategories(brandId));
        model.addAttribute("configItemsMap",
                databaseService.getAddConfigItems(brandId));
        return "addConfig";
    }

我想对这个方法进行单元测试,看看模型是否具有我们期望的属性。
这是我现在的单元测试:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
public class AddConfigurationTest {
    @Autowired
    AddConfigurationController addConfigurationController;

    @MockBean
    DatabaseService databaseServiceTest;
    @Mock
    WebRequest webRequest;

    @Before
    public void setup() {       
        // Make Categories
        List<ItemCategory> defaultCategories = new ArrayList<>();
        defaultCategories.add(new ItemCategory(1, 1, "GPS settings"));

        // Mock it
        Mockito.when(this.databaseServiceTest.getCategories(1)).thenReturn(
            defaultCategories);
    }

    @Test
    public void configurationFormShouldContainCategories() {
        // TODO: Still needs param for webrequest

        // Make a model
        Model model = new ExtendedModelMap();
        addConfigurationController.showConfigurationForm(webRequest, model);
        // Get the list from the model
        @SuppressWarnings("unchecked")
        List<ItemCategory> categoryList = (List<ItemCategory>) model.asMap()
            .get("categoryResult");
        System.out.println(categoryList);
    }
}

System.out.println 现在输出:[]

我确信它与 WebRequest 有关,因为我现在拥有它,这个 WebRequest 没有来自 showConfigurationForm 方法所需的表单的输入。

我的问题是:如何将正确的数据添加到 WebRequest 以便测试返回一个列表?还是有其他我没有想到的方法?

【问题讨论】:

    标签: java forms spring-boot junit


    【解决方案1】:

    在执行测试之前配置你的 Mock WebRequest 对象:

        @Before
        public void setup()
        {
            Map<String, String[]> mockParameterMap = new HashMap<>();
            mockParameterMap.put("brand00", new String[]{"value01"});
            // add all the parameters you want ...
            Mockito.when(webRequest.getParameterMap())
                    .thenReturn(mockParameterMap);
        }
    

    对于您描述的示例,这应该足够了。

    【讨论】:

      【解决方案2】:

      也可以使用MockHttpServletRequest.html以你想要的方式设置http请求。

      MockHttpServletRequest servletRequest = new MockHttpServletRequest();
      servletRequest.setServerName("www.example.com");
      servletRequest.setRequestURI("/v1/someuri");
      servletRequest.addParameter("brand1", "value1");
      servletRequest.addParameter("brand2", "value2");
      servletRequest.addParameter("another-param", "another-value");
      
      ServletWebRequest servletWebRequest = new ServletWebRequest(servletRequest);
      
      assertThat("brand names ", servletWebRequest.getParameterMap(), hasEntry("brand1", "value1"));
      

      它在 ServletWebRequest 的情况下特别有用,例如,其 'getRequestURI()' 方法是最终方法,因此不能被模拟。因此,我们可以简单地传入我们构建的 Web 请求,而不是模拟,就像上面的那样。

      【讨论】:

        猜你喜欢
        • 2018-12-13
        • 1970-01-01
        • 2017-10-04
        • 2016-05-28
        • 1970-01-01
        • 2014-06-28
        • 2020-08-15
        • 1970-01-01
        相关资源
        最近更新 更多