Steps to use Mockito to test Java functions: Add Mockito dependencies. Create mock objects and set mock behavior. Call the function to be tested. Assert the expected behavior of a function. Use verify() to verify simulated interactions.
How to use Mockito for unit testing of Java functions
Mockito is a popular mock when it comes to unit testing in Java Framework that allows you to create test doubles to mock external dependencies. Testing Java functions is very easy with Mockito.
Dependencies
Before you start, make sure you include the Mockito dependencies in your project:
<dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>4.6.1</version> <scope>test</scope> </dependency>
Create the test class
To create a function test class, create a new class and extend the MockitoTestCase
class as follows:
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class FunctionTest extends MockitoTestCase { // 定义要测试的函数 private Function<Integer, Integer> function; @Before public void setUp() { // 创建函数的模拟 function = Mockito.mock(Function.class); } // 测试函数的行为 @Test public void testFunction() { // 设置函数的模拟行为 Mockito.when(function.apply(10)).thenReturn(20); // 调用要测试的函数 int result = function.apply(10); // 断言函数的预期行为 assertEquals(20, result); verify(function, times(1)).apply(10); } }
Practical case
Let's consider a simple function addTen()
that accepts a number and returns a result plus 10.
public class MathFunctions { public int addTen(int number) { return number + 10; } }
Test actual case
To test this function using Mockito, please create a test class as shown below:
import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class MathFunctionsTest extends MockitoTestCase { private MathFunctions mathFunctions; @Before public void setUp() { mathFunctions = Mockito.mock(MathFunctions.class); } @Test public void testAddTen() { Mockito.when(mathFunctions.addTen(10)).thenReturn(20); int result = mathFunctions.addTen(10); assertEquals(20, result); verify(mathFunctions, times(1)).addTen(10); } }
Conclusion
Using Mockito to unit test Java functions is very simple. You can easily test the correctness of a function by creating a mock, defining the mock's behavior, and asserting the function's expected behavior.
The above is the detailed content of How to unit test Java functions with Mockito?. For more information, please follow other related articles on the PHP Chinese website!