使用Spring Clound合约编写云合约端点的生产者测试

问题描述

我正在将Spring云合同写到现有项目中。当我到达终点时,它可以正常工作,但是我面临着为生产者设置消息传递方面的问题。

在我的控制器中,我具有以下代码

 {

    
    
    StudentInfo studentInfo = new StudentInfo();
    studentInfo.setProfileId(studId);
    studentInfo.setClassDetails(studentService.getClassDetailsInfo(studId));
    
         
    studentInfo.setMarksInfo(studentService.getMarksInfo(studId)); 
    
    return employerInfo; }
} 

这是控制器中无法更改的现有端点代码

由于该方法调用了两个服务调用,所以我无法理解如何编写生产者方法,该方法可以模拟服务响应并构造JSON。

这是我的生产者代码

StudentInfo mockStudentsResponse = JUnitTestUtil
      .toObject(JUnitTestUtil.getFile("studentInfo.json"),StudentInfo .class); // This student info has two class objects inside it 1. ClassDetails and 2.MarksInfo 
    //How can I mock the response and to which service class

任何想法都将不胜感激。

解决方法

您应该模拟控制器内部的服务。当我说服务时,我指的是应用程序服务。您的控制器应该模拟了应用程序服务。这样,您将请求发送到控制器,然后该请求的处理在控制器中结束。它不会降到其他任何层次,更不用说在其他应用中被调用了。

示例

@RestController
class MyController {
  private final Service1 service1;
  private final Service2 service2;


  @GetMapping("/bla")
  String bla() {
    String a = service1.a();
    String b = service2.b(a);
    return a + b;
  }
}

然后在基类中完成

class MyBaseClass {

  Service1 service1 = Mockito.mock(Service1.class);
  Service2 service2 = Mockito.mock(Service2.class);

  @BeforeEach
  void setup() {
    Mockito.when(service1.a()).thenReturn("foo");
    Mockito.when(service2.b()).thenReturn("bar");
    RestAssuredMockMvc.standaloneSetup(new MyController(service1,service2));
  }
}