在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()之前,否则不生效。
在WebMvcTest中使用其他的Bean时,可以使用@MockBean进行模拟。
版权归原作者 落寞无缘 所有, 如有侵权,请联系我们删除。