📜  如何使用 Mockito 和 Junit 在Java应用程序中编写测试用例?

📅  最后修改于: 2022-05-13 01:54:40.784000             🧑  作者: Mango

如何使用 Mockito 和 Junit 在Java应用程序中编写测试用例?

莫基托 是一个用于对Java应用程序进行单元测试的开源测试框架。它在开发可测试的应用程序中起着至关重要的作用。 Mockito 用于模拟接口,以便可以将虚拟功能添加到可在单元测试中使用的模拟接口。单元测试是一种软件测试,其中测试软件的各个组件。使用 Mockito 框架的主要目标是通过模拟外部依赖项并在测试代码中使用它们来简化测试的开发。因此,Mockito 提供了更简单的测试代码,更易于理解、可读性和可修改性。 Mockito 还可以与JUnitTestNG等其他测试框架一起使用。

分步实施

第 1 步:在您喜欢的Java IDE 中创建一个 Maven 项目(这里我们使用的是 IntelliJ IDEA)

第 2 步:成功创建 maven 项目后,您必须在pom.xml文件中添加一些依赖项。我们必须在您的 pom.xml 文件中添加以下依赖项。

Mockito 的依赖为 如下

XML

    org.mockito
    mockito-all
    2.0.2-beta


XML

    junit
    junit
    4.8.2


XML


    4.0.0
  
    org.example
    mockito-demo
    1.0-SNAPSHOT
  
    
        
            junit
            junit
            4.8.2
        
        
            org.mockito
            mockito-all
            2.0.2-beta
        
    
  
    
        11
        11
    
  


Java
// Java Program to Illustrate TodoService File
  
// Importing List class
import java.util.List;
  
// Interface
public interface TodoService {
  
    // Creating a simple method retrieveTodos()
    public List retrieveTodos(String user);
}


Java
// Java Program to Illustrate TodoServiceImpl File
  
// Importing required classes
import java.util.ArrayList;
import java.util.List;
  
// Main class
public class TodoServiceImpl {
  
    // Creating a reference of
    // TodoService interface
    private TodoService todoService;
  
    // Constructor
    public TodoServiceImpl(TodoService todoService)
    {
  
        // This keyword refers to same instance itself
        this.todoService = todoService;
    }
  
    // Method
    // Filtering the string
    public List
    retrieveTodosRelatedToJava(String user)
    {
  
        List filteredTodos
            = new ArrayList();
        List todos
            = todoService.retrieveTodos(user);
  
        for (String todo : todos) {
  
            // Filtering the string that contains "Java"
            // keyword
            if (todo.contains("Java")) {
                filteredTodos.add(todo);
            }
        }
        return filteredTodos;
    }
}


Java
// Java Program to Illustrate TodoServiceImplMockTest File
  
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
  
// Importing required classes
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
  
// MockitoJUnitRunner gives automatic validation
// of framework usage, as well as an automatic initMocks()
@RunWith(MockitoJUnitRunner.class)
  
// Main class
public class TodoServiceImplMockTest {
  
    TodoServiceImpl todoBusiness;
  
    // The Mockito.mock() method allows us to
    // create a mock object of a class or an interface
    @Mock TodoService todoServiceMock;
  
    // Methods annotated with the @Before
    // annotation are run before each test
    @Before public void setUp()
    {
        todoBusiness = new TodoServiceImpl(todoServiceMock);
    }
  
    // @Test
    // Tells the JUnit that the public void method
    // in which it is used can run as a test case
    @Test
    public void testRetrieveTodosRelatedToSpring_usingMock()
    {
        List todos
            = Arrays.asList("Learn Spring", "Lear Java",
                            "Learn Spring Boot");
        when(todoServiceMock.retrieveTodos("User"))
            .thenReturn(todos);
  
        List filteredTodos
            = todoBusiness.retrieveTodosRelatedToJava(
                "User");
        assertEquals(1, filteredTodos.size());
    }
  
    @Test
    public void
    testRetrieveTodosRelatedToSpring_withEmptyList_usingMock()
    {
        List todos = Arrays.asList();
        when(todoServiceMock.retrieveTodos("Dummy"))
            .thenReturn(todos);
  
        List filteredTodos
            = todoBusiness.retrieveTodosRelatedToJava(
                "Dummy");
        assertEquals(0, filteredTodos.size());
    }
}


Junit 的依赖为 如下

XML


    junit
    junit
    4.8.2

实现:下面是pom.xml 文件的完整代码

XML



    4.0.0
  
    org.example
    mockito-demo
    1.0-SNAPSHOT
  
    
        
            junit
            junit
            4.8.2
        
        
            org.mockito
            mockito-all
            2.0.2-beta
        
    
  
    
        11
        11
    
  

第 3 步:现在您必须创建一个名为TodoService的接口和一个名为TodoServiceImpl 的类。

Java

// Java Program to Illustrate TodoService File
  
// Importing List class
import java.util.List;
  
// Interface
public interface TodoService {
  
    // Creating a simple method retrieveTodos()
    public List retrieveTodos(String user);
}

Java

// Java Program to Illustrate TodoServiceImpl File
  
// Importing required classes
import java.util.ArrayList;
import java.util.List;
  
// Main class
public class TodoServiceImpl {
  
    // Creating a reference of
    // TodoService interface
    private TodoService todoService;
  
    // Constructor
    public TodoServiceImpl(TodoService todoService)
    {
  
        // This keyword refers to same instance itself
        this.todoService = todoService;
    }
  
    // Method
    // Filtering the string
    public List
    retrieveTodosRelatedToJava(String user)
    {
  
        List filteredTodos
            = new ArrayList();
        List todos
            = todoService.retrieveTodos(user);
  
        for (String todo : todos) {
  
            // Filtering the string that contains "Java"
            // keyword
            if (todo.contains("Java")) {
                filteredTodos.add(todo);
            }
        }
        return filteredTodos;
    }
}

第 4 步:现在我们将对TodoServiceImpl中的retrieveTodosRelatedToJava()方法执行单元测试。 Java文件。要创建测试类,请按照以下步骤操作。首先在TodoServiceImpl 里面右击。 Java文件。

然后单击生成按钮。

然后点击测试按钮。

例子:

Java

// Java Program to Illustrate TodoServiceImplMockTest File
  
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
  
// Importing required classes
import java.util.Arrays;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
  
// MockitoJUnitRunner gives automatic validation
// of framework usage, as well as an automatic initMocks()
@RunWith(MockitoJUnitRunner.class)
  
// Main class
public class TodoServiceImplMockTest {
  
    TodoServiceImpl todoBusiness;
  
    // The Mockito.mock() method allows us to
    // create a mock object of a class or an interface
    @Mock TodoService todoServiceMock;
  
    // Methods annotated with the @Before
    // annotation are run before each test
    @Before public void setUp()
    {
        todoBusiness = new TodoServiceImpl(todoServiceMock);
    }
  
    // @Test
    // Tells the JUnit that the public void method
    // in which it is used can run as a test case
    @Test
    public void testRetrieveTodosRelatedToSpring_usingMock()
    {
        List todos
            = Arrays.asList("Learn Spring", "Lear Java",
                            "Learn Spring Boot");
        when(todoServiceMock.retrieveTodos("User"))
            .thenReturn(todos);
  
        List filteredTodos
            = todoBusiness.retrieveTodosRelatedToJava(
                "User");
        assertEquals(1, filteredTodos.size());
    }
  
    @Test
    public void
    testRetrieveTodosRelatedToSpring_withEmptyList_usingMock()
    {
        List todos = Arrays.asList();
        when(todoServiceMock.retrieveTodos("Dummy"))
            .thenReturn(todos);
  
        List filteredTodos
            = todoBusiness.retrieveTodosRelatedToJava(
                "Dummy");
        assertEquals(0, filteredTodos.size());
    }
}