Mockito 使用 doAnswer 自定义方法处理逻辑
doAnswer 的作用和 thenAnswer 相同,但使用方式不同:
import org.junit.Assert; import org.junit.Test; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.Random; import static org.mockito.Mockito.*; public class MockitoDemo { @Test public void test() { MockitoAnnotations.initMocks(this); Random random = mock(Random.class); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return 1; } }).when(random).nextInt(); Assert.assertEquals(1, random.nextInt()); } }
转载:https://www.letianbiji.com/java-mockito/mockito-doanswer.html