MockBean 單元測試


案例一   官方文檔:https://docs.spring.io/spring-boot/docs/2.0.4.RELEASE/reference/htmlsingle/


import org.junit.*;

import org.junit.runner.*;
import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.autoconfigure.web.servlet.*; import org.springframework.boot.test.mock.mockito.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class)
/**使用webMvcTest工具測試,UserVehicleControkker.class代表對
UserVehicleControkker 進行測試*/
@WebMvcTest(UserVehicleController.class)

public class MyControllerTests { @Autowired private MockMvc mvc; @MockBean private UserVehicleService userVehicleService; @Test public void testExample() throws Exception { given(this.userVehicleService.getVehicleDetails("sboot")) .willReturn(new VehicleDetails("Honda", "Civic")); this.mvc.perform(get("/sboot/vehicle").accept(MediaType.TEXT_PLAIN)) .andExpect(status().isOk()).andExpect(content().string("Honda Civic")); } }

案例二:jsons數據的傳遞,即傳一個對象

官方文檔的推薦:
import org.junit.*;
import org.junit.runner.*; import org.springframework.beans.factory.annotation.*; import org.springframework.boot.test.autoconfigure.json.*; import org.springframework.boot.test.context.*; import org.springframework.boot.test.json.*; import org.springframework.test.context.junit4.*; import static org.assertj.core.api.Assertions.*; @RunWith(SpringRunner.class) @JsonTest public class MyJsonTests { @Autowired private JacksonTester<VehicleDetails> json; 
/**方式一/ @Test public void testSerialize() throws Exception { VehicleDetails details = new VehicleDetails("Honda", "Civic"); // Assert against a `.json` file in the same package as the test assertThat(this.json.write(details)).isEqualToJson("expected.json"); // Or use JSON path based assertions assertThat(this.json.write(details)).hasJsonPathStringValue("@.make"); assertThat(this.json.write(details)).extractingJsonPathStringValue("@.make") .isEqualTo("Honda"); } /**方式二/ @Test public void testDeserialize() throws Exception {
/**自己制作一些json數據*/ String content = "{\"make\":\"Ford\",\"model\":\"Focus\"}";
/**使用預言:第一個:
assertThat進行數據的json格式的轉換,以及傳遞數據*/
assertThat(this.json.parse(content)) .isEqualTo(new VehicleDetails("Ford", "Focus"));
/**使用預言:assertThat:傳遞數據,並得到自己制作的數據,並且期望返回的數據是否是 “Ford”*/
assertThat(this.json.parseObject(content).getMake()).isEqualTo("Ford");
}
}
/*個人的json數據:包裝成一個對象,傳遞過去*/
1):需要的依賴:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.12</version>
</dependency>


2):
源代碼:
package hsbc.team03.ordersystem.displayproduct;

import com.alibaba.fastjson.JSONObject;
import hsbc.team03.ordersystem.displayproduct.common.UUIDUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
* @Author:Evan
* @Date:2018/8/7 11:01
* @Describe:
* @Return:
* @Param:
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class ManagerControllerTest {
@Autowired
private WebApplicationContext context;
private MockMvc mvc;

/**使用mockBean模擬ManagerServiceImpl層 ,注意ManagerServiceImpl 是自己創建的一個類*/
    @MockBean
private ManagerServiceImpl managerServiceImpl;

@Before
public void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(context).build();
}
 
 @Test
public void managerAddProduct() throws Exception {
Mockito.when(managerServiceImpl.addProduct(Mockito.any(Product.class))).thenReturn(true);

/**制造數據,即對象*/
Product product = new Product();
product.setId(UUIDUtils.getUUID());
product.setProductCode("231701");
product.setProductName("中海");
product.setProductPrice(20.8);
product.setProductType("穩健型");
product.setDescription("這是1");
product.setStatus(1);
product.setProductDeadline("2018-8-10");

/**將對象進行轉換成json格式*/
String requestJson = JSONObject.toJSONString(product);

mvc.perform(
/**post方法、訪問的路徑*/
post("/manager/add/products")
.contentType(MediaType.APPLICATION_JSON_UTF8) /*數據格式*/
.content(requestJson) /*內容,即參數*/
.accept(MediaType.APPLICATION_JSON)) /*接收返回的參數是json格式*/
.andExpect(status().isOk()) /*status().isOk(),期望返回的狀態碼是200*/
.andDo(print()); /*控制台打印*/


}
}



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM