如何测试需要模型作为参数的方法(Java,Spring Boot)

How to test a method that requires a model as a argument (Java, Springboot)

我是 JUnit 测试方法的新手。我目前正在开发一个 Springboot 应用程序,我现在想对其进行正确测试。但是,我不明白需要做什么才能测试以模型为参数的方法。

我要测试的方法:

public void updateCheckoutIncome(Model model, MonetaryAmount amount) {
        checkoutIncome = checkoutIncome.add(amount);
        model.addAttribute("checkoutIncome", checkoutIncome);
    }

然后我继续写了这个应该测试上面 class 的测试文件:

public class AccountingManagementTest {

    @SpringBootTest
    @AutoConfigureMockMvc
    public class AccountingControllerTest {

        @Autowired
        MockMvc mvc;
        @Autowired
        AccountingManagement accountingManagement;


        
        @Test
        @WithMockUser(roles = "BOSS,EMPLOYEE")
        void updateCheckoutIncomeTest() throws Exception {

            MonetaryAmount checkoutIncome = Money.of(10.00, EURO);
            Model cart = new ModelAttribute("cart");

            accountingManagement.updateCheckoutIncome(cart, Money.of(19.99, EURO));
            Assertions.assertEquals(Money.of(29.99, EURO), checkoutIncome);

        }
    }
}

我的问题是:我如何测试创建“模型”,我需要传递给测试中的方法调用?我可以找到创建新“ModelAndView”元素的方法,但我的方法需要一个“Model”元素。谁能指导我缺少什么?

稍微解释一下模型:这个在springboot中定义了一个视图元素。例如,如果您有一个模型“购物车”,它包含将被传递到 HTML 文件(例如)的信息。

我认为在这种情况下,您应该使用 ArgumentCaptor,它将捕获您传递给方法 (updateCheckoutIncome) 的参数(模型),然后您可以验证模型的属性值。

有关详细信息,请查看本教程:

https://www.baeldung.com/mockito-argumentcaptor