在Spring Cloud中进行Controller的单元测试,使用Junit5和Mock。
Controller:
@RestController
@RefreshScope
public class AccountController {
@PostMapping("/login")
void login(@RequestBody User user) {
System.out.println(user.getPassword());
System.out.println("login");
}
}
方式一:使用@SpringBootTest + @AutoConfigureMockMvc
@SpringBootTest
@AutoConfigureMockMvc
class AccountControllerTest {
@Autowired
MockMvc mockMvc;
public static String asJsonString(Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
void testLogin() throws Exception {
User user = userObject();
mockMvc.perform(post("/login")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(user)))
.andExpect(status().isOk()).andReturn();
}
private User userObject() {
String username = "user";
String password = "password";
return new User(username, password);
}
}
方式二:使用@WebMvcTest + @ImportAutoConfiguration(RefreshAutoConfiguration.class)
解决No Scope registered for scope name 'refresh'异常
java.lang.IllegalStateException: No Scope registered for scope name 'refresh'
@WebMvcTest(AccountController.class)
@ImportAutoConfiguration(RefreshAutoConfiguration.class)
class AccountControllerTest {
@Autowired
MockMvc mockMvc;
public static String asJsonString(Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
void testLogin() throws Exception {
User user = userObject();
mockMvc.perform(post("/login")
.header("key","value")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(user)))
.andExpect(status().isOk()).andReturn();
}
private User userObject() {
String username = "user";
String password = "password";
return new User(username, password);
}
}
注入Mockmvc方式有两种
方式一:(@AutoConfigureMockMvc / @WebMvcTest) + @Autowired
方式二:
@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new AccountController()).build();
}
注意:在使用Mockito.when打桩时注意顺序,需要在mockMvc.perform()之前,否则不生效。文章来源:https://www.toymoban.com/news/detail-573170.html
在WebMvcTest中使用其他的Bean时,可以使用@MockBean进行模拟。文章来源地址https://www.toymoban.com/news/detail-573170.html
到了这里,关于Spring Cloud中Controller单元测试 Junit5 & MockMvc的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!