无论如何可以为我的 RestController 编写单元测试而不使用 @MockBean 模拟服务?
@Autowired
private MockMvc mockMvc;
@MockBean
private CarService carService;
@Test
public void shouldReturnCarDetails() {
//when(carService.getCarDetails(1)).thenReturn(new Car(1, 300));
try {
mockMvc.perform(MockMvcRequestBuilders.get("/api/cars/1")).andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("speed").value(300));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}`
还有另一个选项称为@EnableWebMvc/mockMvc,您可以通过它测试控制器层。
下面给出的代码片段,
/*
* The TransactionsControllerTest class implements Junit functionality that
* simply connect to the controller layer (TransactionsController) and test the
* controller layer with some pre-defined/test value. This class also provides
* the details result for each test cases.
*
* @author Sibsankar Bera
* @version 1.0
* @since 2018-08-31
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TransactionsController.class, AppConfig.class, AppInitializer.class })
@EnableWebMvc
public class TransactionsControllerTest {
private static final Logger logger = Logger.getLogger(TransactionsControllerTest.class.getName());
private MockMvc mockMvc = null;
String values = null;
@InjectMocks
private WebApplicationContext wac;
/**
* This Junit test method assigns required resources value before use.
*/
@Before
public void setup() throws Exception {
values = TransactionConstant.AUTHORIZATION_CODE;
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
/**
* This Junit test method is used to test controller layer api,
* "/transactions/getAllTransactionList"
*/
@Test
public void getAllTransactionList_Test() {
try {
logger.info("Logger Name: getAllTransactionList_Test() :: " + logger.getName());
ObjectMapper mapper = new ObjectMapper();
MvcResult result = mockMvc.perform(get("/getAllTransactionList").header("authorization_code", values))
.andReturn();
JsonNode root = mapper.readTree(result.getResponse().getContentAsString());
JsonNode resultNodes = root.path("result");
logger.debug("Junit Response :: resultNodes :: getAllTransactionList_Test() :: " + resultNodes.asText());
assertEquals(resultNodes.asText(), "success");
} catch (Exception e) {
logger.error("Junit :: Exception :: getAllTransactionList_Test() :: ", e);
}
}