[英]How to configure field annotated with @Mock in Spring Boot Unit test
我试图通过@RestController
注入其中的@Service
来测试@RestController
。 我能够向模拟服务发出请求,但似乎无法自定义其模拟行为。 是否不能结合@Mock
和doThrow(...)
? 还是我的 when 子句有问题?
我的代码:
@SpringBootTest
class LessonControllerTests {
private MockMvc mockMvc;
@Mock
private LessonService service;
@InjectMocks
private LessonController controller;
@Test
public void some_good_test_name() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
Mockito.doThrow(new SignUpFailed("Test fail"))
.when(service).addAttendeeToLesson(
Mockito.any(Attendee.class), Mockito.anyString(), Mockito.anyString()
);
final String requestJson = """
{
"email": "email@example.com",
"name": "John Doe",
"message": "Hello"
}
""";
mockMvc.perform(
post("/lessons/123/attendees")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(requestJson)
)
.andExpect(status().isOk())
.andExpect(content().json("{}"));
}
}
问题是服务调用的第二个参数是一个由@Value 注入的字符串,所以在测试中它变成了 null 并且 anyString 与它不匹配。
我没有使用 ReflectionUtils 来设置这个 @Value 字段的值,而是将我的 Controller 重写为使用构造函数注入,将 @Autowired 和 @Value 注释移动到构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.