2016-12-22 52 views
0

我正在写unittests,我偶然发现了一些东西,我找不到适合我需求或我已有的代码的解决方案。带WebRequest的Spring Boot单元测试,包含表单提交

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

,品牌的选择是一种形式,它提交给此方法:

// 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,以便测试将返回一个List?还是有另一种方法,我还没有想出来?

回答

1

执行测试之前就配置模拟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); 
    } 

这应该是够你描述的例子。