我在使用 MockMvc 時遇到了困難。這里我有簡單的服務和控制器類:
服務:
@Slf4j
@Service
public class EmployeeService {
//...
public Employee GetSample() {
//...
//filling Employee Entities
return new Employee(
"Harriet"
, "random"
, 25);
}
}
控制器:
@RestController
@RequestMapping(value = "/info")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Validated
public class EmployeeController {
private final EmployeeService employeeService;
@PostMapping("/GetEmployee")
public ResponseEntity<Employee> GetEmployee() {
Employee employee = employeeService.GetSample();
return new ResponseEntity<>(employee, HttpStatus.OK);
}
}
測驗:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class EmployeeTestCase {
private MockMvc mockMvc;
@InjectMocks
private EmployeeController EmployeeController;
@Mock
private EmployeeService employeeService;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.standaloneSetup(employeeController).build();
}
@Test
public void getEmployee() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/info/GetEmployee")).andDo(print());
}
}
當我嘗試使用 MockMvc 時,我得到空體。似乎員工是空的。但我不明白為什么。
我認為當測驗使用時perform,它應該初始化員工,然后它不應該為空。我試圖盡可能地減少代碼。我希望不會太久。
注意:也嘗試使用 Mockito.when(employeeController.GetEmployee()).thenCallRealMethod();
uj5u.com熱心網友回復:
@SpringBootTest 批注加載完整的 Spring 應用程式背景關系。這意味著您不會模擬您的層(服務/控制器)。
如果您想測驗應用程式的特定層,您可以查看以下提供的測驗切片注釋Springboot:https : //docs.spring.io/spring-boot/docs/current/reference/html/test-auto-configuration.html
相比之下,test slice注解僅加載測驗特定層所需的 bean。正因為如此,我們可以避免不必要的模擬和副作用。
測驗切片的一個例子是 @WebMvcTest
@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = HelloController.class,
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = SecurityConfig.class)
}
)
public class HelloControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void hello() throws Exception {
String hello = "hello";
mvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string(hello));
}
@Test
public void helloDto() throws Exception {
String name = "hello";
int amount = 1000;
mvc.perform(
get("/hello/dto")
.param("name", name)
.param("amount", String.valueOf(amount)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name", is(name)))
.andExpect(jsonPath("$.amount", is(amount)));
}
}
但是,如果您真的想加載 SpringBoot 應用程式背景關系,例如集成測驗,那么您有幾個選擇:
@SpringBootTest
@AutoConfigureMockMvc
public class TestingWebApplicationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnDefaultMessage() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello, World")));
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class AuctionControllerIntTest {
@Autowired
AuctionController controller;
@Autowired
ObjectMapper mapper;
MockMvc mockMvc;
@Before
public void setUp() throws Exception {
System.out.println("setup()...");
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void create_ValidAuction_ShouldAddNewAuction() throws Exception {
final Auction auction = new Auction(
"Standing Desk",
"Stand up desk to help you stretch your legs during the day.",
"Johnnie34",
350.00);
mockMvc.perform(post("/auctions")
.contentType(MediaType.APPLICATION_JSON)
.content(toJson(auction)))
.andExpect(status().isCreated());
}
}
假設您根本不想加載任何層,并且想要模擬所有內容,例如單元測驗:
@RunWith(MockitoJUnitRunner.class)
class DemoApplicationTest {
@Mock
private UserRepository userRepository;
private Demo noneAutoWiredDemoInstance;
@Test
public void testConstructorCreation() {
MockitoAnnotations.initMocks(this);
Mockito.when(userRepository.count()).thenReturn(0L);
noneAutoWiredDemoInstance = new Demo(userRepository);
Assertions.assertEquals("Count: 0", noneAutoWiredDemoInstance.toString());
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/362646.html
