【问题标题】:Spring test: how to 'pass' model into controller post methodSpring 测试:如何将模型“传递”到控制器 post 方法中
【发布时间】:2017-11-14 14:50:00
【问题描述】:

我正在使用 Spring Boot 并正在尝试为如下所示的控制器编写集成测试:

public String pagerequestSubmit(@ModelAttribute Pagerequest pagerequest, Model model) {
...
 }

现在我正在尝试为这个控制器编写一个集成测试,如下所示:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes=PageAnalyzerInSpringApplication.class)
public class PagerequestControllerIntegrationTest {

@Autowired
PagerequestController pagerequestController;

@Test
public void testHappyPath() {


    Pagerequest mockPageRequest = new Pagerequest();
    mockPageRequest.setUrl("https://www.somedomain.com/");
    ....

    String outcome = pagerequestController.pagerequestSubmit(mockPageRequest);

    assertThat(outcome, is(equalTo("result")));

}

我在执行“模拟页面请求”并将其传递给 post 方法时没有任何问题,所以我已经做到了,但是上面的测试不起作用,因为我得到了:

“PagerequestController类型中的方法pagerequestSubmit(Pagerequest,Model)不适用于参数(Pagerequest)”

这是有道理的,因为我没有传入任何 Model 类型的参数 我完全不知道该怎么做。

我尝试实例化一个不起作用的模型,创建一个同样不起作用的假模型,并传入一个为空的模型变量,这至少可以让测试运行,但随后在控制器中使用模型时抛出空指针异常。

关于如何解决这个问题的任何想法?

提前致谢!

【问题讨论】:

    标签: java spring spring-mvc testing integration-testing


    【解决方案1】:

    您的pagerequestSubmit(@ModelAttribute Pagerequest pagerequest, Model model) 接受两个参数,一个是 pagerequest,另一个是模型,但在您的测试中您只传递了 pagerequest。您还需要传递模型对象。这只是您的测试类中的错误方法签名。 创建模型对象的模拟并将其粘贴到您的代码中

     @Mock
        private Model model;
    
     String outcome = pagerequestController.pagerequestSubmit(mockPageRequest,model);
     assertThat(outcome, is(equalTo("result")));
    

    【讨论】:

    猜你喜欢
    • 2015-08-03
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多