首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Spring Boot控制器中测试模型属性

,可以通过编写单元测试来实现。以下是一个示例代码:

代码语言:txt
复制
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@WebMvcTest(YourController.class)
public class YourControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private YourService yourService;

    @Test
    public void testModelAttribute() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/your-endpoint"))
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.model().attributeExists("yourModelAttribute"))
                .andExpect(MockMvcResultMatchers.model().attribute("yourModelAttribute", "expectedValue"));
    }
}

在上述示例中,我们使用了@WebMvcTest注解来指定要测试的控制器类(YourController)。通过@MockBean注解,我们可以模拟控制器中所依赖的服务(YourService)。在testModelAttribute()方法中,我们使用MockMvc对象发起一个GET请求,并验证返回的状态码是否为200(isOk())。然后,我们使用andExpect()方法来验证模型属性是否存在(attributeExists())以及其值是否符合预期(attribute())。

请注意,上述示例中的YourControllerYourService是示意性的类名,你需要将其替换为实际的控制器和服务类名。另外,你还需要根据实际情况修改/your-endpoint为你要测试的控制器的端点路径。

关于Spring Boot控制器中测试模型属性的更多信息,你可以参考以下链接:

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券