gpt4 book ai didi

java - 使用 WebRequest 进行 Spring Boot 单元测试,包括表单提交

转载 作者:行者123 更新时间:2023-12-02 04:02:20 26 4
gpt4 key购买 nike

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

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

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

// 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 以便测试返回一个列表?还是有另一种我还没有想到的方法?

最佳答案

只需在执行测试之前配置您的 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);
}

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

关于java - 使用 WebRequest 进行 Spring Boot 单元测试,包括表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41283398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com