Search code examples
javaspring-bootjunit

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


I'm new to testing methods with JUnit. I'm currently working on a Springboot application, which I want to test properly now. However, I don't understand what needs to be done in order to test a method that has a model as an argument.

The method I want to test:

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

I then went ahead and wrote this test file that should test the class above:

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);

        }
    }
}

My question is: How do I test create the "model", that I need to pass along to the method call in the test? I could find a method creating a new "ModelAndView" element, but my method requires a "Model" element. Can anyone guide me what I'm missing?

To explain the model a little bit: This defines a view element in springboot. If you're having a model "cart" for example, this contains information which will be passed over to an HTML file (for example).


Solution

  • I think in this case you should use ArgumentCaptor which will capture the argument(model) you passed to your method (updateCheckoutIncome), then you can verify the values of attributes of your model.

    for more details check out this tutorial:

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