<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                # 如何對控制器和服務執行單元測試 > 原文: [https://javatutorial.net/how-to-perform-unit-testing-for-controllers-and-services](https://javatutorial.net/how-to-perform-unit-testing-for-controllers-and-services) 如您所知,測試非常重要。 因此,在本教程中,您將學習如何完成測試!更具體地說,您將學習如何在**控制器和服務上執行該測試**。 ![java-featured-image](https://img.kancloud.cn/05/3e/053ee0bb59842d92359246c98f815e0c_780x330.jpg) ## 控制器 普通控制器執行 2 件事之一: * 渲染視圖 要么 * 處理表單提交 讓我們看一個代碼示例: ```java @RestController @RequestMapping("/employee/account/*") public class EmployeeAccountController { private EmployeeService employeeService; // define the logger to which we will be writing stuff for debugging purposes private static Logger log = LoggerFactory.getLogger(EmployeeAccountController.class); @Autowired public EmployeeAccountController(EmployeeService employeeService) { this.employeeService = employeeService; } @PostMapping(value="/register/process", produces="application/json") public Response registrationProcess(ModelMap model, @RequestBody Employee reqEmployee) { Employee employee = null; try { // try to validate the user using the validate() function defined in the EmployeeService class employee = employeeService.validate(employee.getEmail(), employee.getUsername(), employee.getPassword()); } catch (Exception e) { // if the given information did not match the validate() method criteria then print it out to the console log.debug(e.getMessage(), e); } // return appropriate string message return employee != null ? new Response("Successful registration.") : new Response("Unsuccessful registration."); } } ``` 通過查看上面的代碼片段,您將看到這只是一個普通的`Controller`,它對用戶以表單形式給出的信息進行有效性檢查。 最后,它會根據有效性檢查的響應返回一個字符串,即“成功消息”或“失敗消息”。 很棒! 但它缺少一些東西。 那就是單元測試! 讓我們添加它。 但是,在向您展示代碼之前,我想向您解釋什么是`MockMvc`。 這是一個 Spring MVC 組件,主要用于為控制器組件創建單元測試。 如何使用`MockMvc`的示例代碼片段: ```java private MockMvc name; @MockBean private Service service; @BeforeEach public string doSomething() throws Exception { service = MockMvcBuilders.standaloneSetup(className(service)).build(); } ``` **@MockBean** 注釋可幫助我們在控制器中模擬依賴項。 ### `EmployeeAccountControllerTest.java` ```java @ExtendWith(SpringExtension.class) @Tag("Controller") public class EmployeeAccountControllerTest { private MockMvc mockMvc; @MockBean private EmployeeService employeeService; // define the logger to which we will be writing stuff for debugging purposes @BeforeEach public void test(TestInfo info) throws Exception { mockMvc = MockMvcBuilders.standaloneSetup(new EmployeeAccountController(employeeService)).build(); } @Test @DisplayName("Return some error message text") public void ReturnErrorMessage() throws Exception { Employee emp = new Employee(); emp.setEmail("demo@demo.com"); emp.setUsername("demoname"); emp.setPassword("demo123"); Gson gSon = new Gson(); String gsonEmployee = gSon.toJson(emp); Mockito.when(employeeService.validate("demo@demo.com", "demoname", "demo123")).thenReturn(null); // the result MvcResult result = mockMvc.perform(post("/employee/account/register/process").contentType(MediaType.APPLICATION_JSON).content(gsonEmployee)).andExpect(status().isOk()).andReturn(); MockHttpServletResponse response = result.getResponse(); ObjectMapper mapper = new ObjectMapper(); Response responseString = mapper.readValue(response.getContentAsString(), Response.class); assertTrue(responseString.getCode().equals("Successful registration.")); assertTrue(responseString.getMessage().equals("Please try again!")); } } ``` 基于類的名稱,您已經知道這是控制器的測試類。 **細分** * `@BeforeEach`:在每次單元測試之前運行的代碼 * `@Test`:單元測試本身 * `@DisplayName`:JUnit5 注解,用于為單元測試分配描述性文本 * `@Tag`:可用于測試發現和執行 * `@ExtendWith(.class)`:將 Spring 5 測試上下文框架與 JUnit 5 集成 因此,在上面的代碼中,首先我們使用`@ExtendWith`注解,該注解用于將 Spring 5 測試框架與 JUnit 5 集成在一起。然后,我們使用@Tag 注解,用于指定這是`Test`類。 然后,我們再次使用`@Mockbean`注解,它可以幫助我們模擬依賴項。 然后我們使用`@BeforeEach`注解,該注解表示將在每個單元測試之前在 之前運行的代碼。 在我們的案例中,建立員工服務。 然后,我們使用@Test 注解指定以下方法為`Test`,然后我們也使用`@DisplayName`注解,如上所述,該注解為單元測試方法提供了描述性文本(在代碼段中不是最具描述性的)。 在該方法中,我們將`Employee`實例轉換為 JSON,然后將 Mock 行為設置為每次調用`validate()`時都返回`null`。 然后我們調用控制器方法。 ## 服務 在`Controller`測試示例中,我使用`EmployeeService`作為服務。 現在在本小節中,我們將看到該服務的**實現**。 ### `EmployeeServiceImpl.java` ```java @Service public class EmployeeServiceImpl implements EmployeeService { private EmployeeDAO employeeDAO; @Autowired public EmployeeServiceImpl(EmployeeDAO empDAO) { employeeDAO = empDAO; } @Override public void update(Employee emp) { employeeDAO.update(emp); } // method that checks whether the employee exists or not public boolean exists(String username) throws Exception { List<Employee> employees = (List<Employee>) employeeDAO.findByUsername(username); // check if there are employees matching the given username if (employees.getSize() != 0) { return true; } // throw exception throw new Exception("Employee does not exist in database."); // return false if there are no matches return false; } } ``` **細分** 該類的實現非常簡單–首先,我們創建一個構造函數,該構造函數接受`Employee`數據訪問對象(DAO),并用于分配給我們的私有成員變量。 然后,我們得到了一個`update(Employee)`方法,該方法可以執行此操作–根據作為參數提供的信息(`Employee`)更新雇員記錄。 最后,我們獲得了`exist(String)`方法,該方法檢查具有指定用戶名的員工是否存在。 返回`true`或`false`。 現在,我們為實現創建測試類。 ### `EmployeeServiceTest.java` ```java @ExtendWith(SpringExtension.class) @Tag("Service") public class EmployeeServiceTest { @MockBean private EmployeeDAO employeeDAO; private EmployeeService employeeService; // code run before unit tests @BeforeEach public void test(TestInfo info) throws Exception { employeeService = new EmployeeServiceImpl(employeeDAO); assertTrue(testInfo.getDisplayName().equals("Error message")); } @TestInfo @DisplayName("Error message") public void throwException_When_EmployeeDoesNotExist() { String username = "employee123"; Mockito.when(employeeDao.findByUsername(username)).thenReturn(new ArrayList<User>()); assertThatThrownBy(() -> employeeService.exists(username)).isInstanceOf(Exception.class).hasMessage("Employee does not exist in database."); } } ``` **細分** 我們為`EmployeeService`創建一個`Test`類。 在每個單元測試之前,我們運行`test(TestInfo)`方法,然后運行`throwException_When_EmployeeDoesNotExist()`方法。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看