簡體   English   中英

如何使用 Mockito 和 JUnit 在 Spring 引導中測試 DELETE 方法

[英]How to test DELETE method in Spring boot using Mockito and JUnit

在 Spring 引導框架中,我發現 controller 使用 JUnit 和 Z4D37B33CA816EAC75BC3 進行單元測試的困難我想測試這個方法。 如何測試 DELETE 請求方法:

// 刪除應用程序Controller class

    @DeleteMapping("/applications")
    public String deleteApplicationByObject(@RequestBody Application application) {
        applicationService.deleteById(application.getId());
        return "Deleted";
    }

//刪除應用服務class

    @Override
    @Transactional
    public String removeById(Long id) {
        dao.deleteById(id);
        return "SUCCESS";
    }

// 刪除應用程序道 class

    @Override
    public void deleteById(Long id) {
        Application application = findById(id);
        em.remove(application);
    }

先感謝您。

過了一會兒,我能夠找到我的問題的解決方案,

ApplicationControllerTest.class

package com.spring.addapplication.test.controller;

import static org.mockito.MockitoAnnotations.initMocks;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.spring.addapplication.controller.ApplicationController;
import com.spring.addapplication.model.Application;
import com.spring.addapplication.service.ApplicationService;
import com.spring.addapplication.url.UrlChecker;

@RunWith(SpringJUnit4ClassRunner.class)
public class ApplicationControllerTest {

    @Mock
    ApplicationService applicationService;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        initMocks(this);// this is needed for inititalization of mocks, if you use @Mock 
        ApplicationController controller = new ApplicationController(applicationService,urlChecker);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void deleteApplication() throws Exception {      
        Mockito.when(applicationService.removeById(10001L)).thenReturn("SUCCESS");
        mockMvc.perform(MockMvcRequestBuilders.delete("/applications", 10001L))
                .andExpect(status().isOk());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM