📜  mockito throw exception void 方法 - Java (1)

📅  最后修改于: 2023-12-03 15:17:40.237000             🧑  作者: Mango

Mockito: Mocking void methods and throwing exceptions

Mockito is a popular Java testing framework that enables developers to create mock objects for unit tests. One of the most common use cases for Mockito is mocking a void method and throwing an exception to test error handling in the code being tested.

Here's an example of how to mock a void method and throw an exception using Mockito:

import org.junit.Test;
import org.mockito.Mockito;

public class ExampleTest {

    @Test(expected = RuntimeException.class)
    public void testVoidMethodWithException() {
        // create mock object
        MyClass myMock = Mockito.mock(MyClass.class);

        // set mock object behavior
        Mockito.doThrow(new RuntimeException()).when(myMock).voidMethod();

        // call the method being tested
        MyClassUnderTest myTest = new MyClassUnderTest();
        myTest.callVoidMethod(myMock);
    }
}

// The class being tested
public class MyClassUnderTest {

    public void callVoidMethod(MyClass myClass) {
        // call the void method on the mock object
        myClass.voidMethod();
    }
}

// The class defining the void method
public class MyClass {

    public void voidMethod() {
        // do something
    }
}

In this example, we create a mock object of the MyClass class and then set the behavior for the voidMethod() to throw a RuntimeException. We then call the method being tested (callVoidMethod()) on an instance of the class being tested (MyClassUnderTest), passing in the mock object as a parameter.

The @Test(expected = RuntimeException.class) annotation on the test method indicates that we expect a RuntimeException to be thrown when the method is called. If the exception is not thrown, the test will fail.

Mocking void methods and throwing exceptions with Mockito can help identify bugs and edge cases in your code, allowing you to write more robust and reliable software.