简体   繁体   English

如何在 Spring Cloud 合同的生产者上模拟控制器中的服务

[英]how to mock the service in controller on producer for spring cloud contract

I've been trying to mock the service inside the controller on the producer side我一直在尝试在生产者端模拟控制器内的服务

@Autowired
private Service service;

    @PostMapping(path = "/getone", consumes = "application/json", produces = "application/json")
public ResponseEntity<Response> getone(@RequestBody Test[] test) {
    String appId = Utils.getId();
    return new ResponseEntity<>(service.pub(test,id), HttpStatus.OK);
}

Here's how my base test class look like这是我的基本测试类的样子

@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@SpringBootTest
@RunWith(PowerMockRunner.class)
public class ContractTest {
    
    @Autowired
    private WebApplicationContext context;

    @Mock
    private Service service;

    @BeforeEach
    void setup() {
        mockStatic(Utils.class);
        when(Utils.getId()).thenReturn("194");
       Mockito.when(service.pub(Mockito.any(Test[].class),eq("194"))).thenReturn(TestUtils.publish_success_response());
StandaloneMockMvcBuilder standaloneMockMvcBuilder = MockMvcBuilders.standaloneSetup(publishApiController, this.publishService);
RestAssuredMockMvc.standaloneSetup(standaloneMockMvcBuilder);
    }
  1. The actual service class runs here instead of the mock which is causing the issue?实际的服务类在这里运行而不是导致问题的模拟?
    2.How do we test the failure scenarios in the @Before method ? 2.我们如何测试@Before方法中的失败场景?

There is an important difference between @Mock and @MockBean . @Mock 和 @MockBean 之间有一个重要的区别。 For your test you need @MockBean as you are replacing a Spring bean with a mock for your Spring Test Context.对于您的测试,您需要@MockBean因为您要用 Spring 测试上下文的模拟替换 Spring bean。

Apart from this, you are mixing JUnit 4 ( @RunWith ) and JUnit 5 ( @ExtendWith , @BeforeEach ).除此之外,您还混合了 JUnit 4( @RunWith )和 JUnit 5( @ExtendWith@BeforeEach )。

If you just want to write a test for your controller using MockMvc , you don't have to start the whole Spring Context with @SpringBootTest .如果你只是想编写使用控制器测试MockMvc ,你不必开始与整个Spring上下文@SpringBootTest Spring Boot Test provides an annotation to onlystart a sliced context for your MVC components: @WebMvcTest . Spring Boot Test 提供了一个注解来只为你的 MVC 组件启动一个切片上下文@WebMvcTest

For the static mock of your Utils class, you can use Mockito (since version 3.4.0) to reduce the number of additional dependencies and stick to what the Spring Boot Starter Test provides.对于Utils类的静态模拟,您可以使用Mockito(自 3.4.0 版起)来减少附加依赖项的数量并坚持使用 Spring Boot Starter Test 提供的内容。

A possible test can look like the following:可能的测试如下所示:

// @ExtendWith(SpringExtension.class) not needed with recent Spring Boot versions
@ActiveProfiles("test")
@WebMvcTest
public class ContractTest {
    
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private Service service;

    @Test
    void test() {
      
     try(MockedStatic<Utils> mockedUtils = Mockito.mockStatic(Utils.class)) {
        mockedUtils.when(Utils::getId).thenReturn("194");

        when(service.pub(Mockito.any(Test[].class),eq("194"))).thenReturn(TestUtils.publish_success_response());
        // ... your test
     }
      
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Cloud Contract:如何防止Producer破坏消费者? - Spring Cloud Contract: how to prevent Producer to break consumers? 如何在Spring Cloud Contract存根上获取服务状态 - How to get service state on spring cloud contract stub Spring 云合约无法在生产者端生成 json - Spring Cloud Contract can not produce json in producer side Spring 云合约:基于合约的测试根本不会在生产者端生成 - Spring cloud contract: tests based on contracts are not generated on producer side at all 通过模拟服务进行弹簧控制器测试 - spring controller test by mock service 使用 Spring 云合约为云合约端点编写生产者测试 - Writing producer test for cloud contract end point using Spring clound contract 如何在 mockito 中模拟控制器的服务 - How to mock a service for controller in mockito Spring Cloud Contract 测试是否应该实际调用外部服务? - Should Spring Cloud Contract tests actually call an external service? 我们是否需要在Spring Cloud Contract中存根其他微服务 - Do we need to stub the other micro service in Spring cloud contract 如何在 spring-cloud-gateway 合约测试中从 spring-cloud-contract 中设置带有 StubRunner 端口的 url - How to set urls with port of StubRunner from spring-cloud-contract in spring-cloud-gateway contract tests
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM