【发布时间】: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