亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用springboot編寫rest controller、service和dao層的junit

如何使用springboot編寫rest controller、service和dao層的junit

飲歌長嘯 2023-06-21 14:44:08
如何為RestController、Service和DAO 層編寫JUnit測試用例?我試過了MockMvc@RunWith(SpringRunner.class)public class EmployeeControllerTest {    private MockMvc mockMvc;    private static List<Employee> employeeList;    @InjectMocks    EmployeeController employeeController;    @Mock    EmployeeRepository employeeRepository;    @Test    public void testGetAllEmployees() throws Exception {        Mockito.when(employeeRepository.findAll()).thenReturn(employeeList);        assertNotNull(employeeController.getAllEmployees());        mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/employees"))                .andExpect(MockMvcResultMatchers.status().isOk());    }如何驗證其余控制器和其他層內的CRUD方法?
查看完整描述

1 回答

?
炎炎設計

TA貢獻1808條經驗 獲得超4個贊

您可以使用服務層模擬DAO 層@RunWith(MockitoJUnitRunner.class)組件來進行單元測試。你不需要它。SpringRunner.class


? ? @RunWith(MockitoJUnitRunner.class)

? ? public class GatewayServiceImplTest {


? ? ? ? @Mock

? ? ? ? private GatewayRepository gatewayRepository;


? ? ? ? @InjectMocks

? ? ? ? private GatewayServiceImpl gatewayService;


? ? ? ? @Test

? ? ? ? public void create() {

? ? ? ? ? ? val gateway = GatewayFactory.create(10);

? ? ? ? ? ? when(gatewayRepository.save(gateway)).thenReturn(gateway);

? ? ? ? ? ? gatewayService.create(gateway);

? ? ? ? }

? ? }

您可以用于@DataJpaTest與DAO 層進行集成測試


? ? @RunWith(SpringRunner.class)

? ? @DataJpaTest

? ? public class GatewayRepositoryIntegrationTest {


? ? ? ? @Autowired

? ? ? ? private TestEntityManager entityManager;


? ? ? ? @Autowired

? ? ? ? private GatewayRepository gatewayRepository;


? ? ? ? // write test cases here? ? ?

? ? }


查看完整回答
反對 回復 2023-06-21
  • 1 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號