[英]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);
}
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.