mockito.when().thenreturn()
时间: 2023-04-30 21:03:03 浏览: 267
Mockito 是一个用于 Java 的 mocking 框架。when().thenReturn() 方法用于指定当调用某个方法时,返回指定的结果。这样可以在测试中模拟依赖对象的行为。
例如:
```
Foo mockFoo = mock(Foo.class);
when(mockFoo.bar()).thenReturn(5);
assertEquals(5, mockFoo.bar());
```
这段代码中,我们创建了一个 Foo 类型的 mock 对象,并通过 when(mockFoo.bar()).thenReturn(5) 指定当 mockFoo.bar() 被调用时返回 5。然后我们断言 mockFoo.bar() 的返回值是 5。
相关问题
mockito.when返回值是void
当Mockito.when()方法返回void时,通常是因为我们在模拟一个void方法。这意味着我们不能使用thenReturn()方法来指定返回值,而是应该使用doNothing()或doThrow()等方法来模拟方法的行为。例如:
```
Mockito.doNothing().when(mockObject).voidMethod();
```
这将模拟一个voidMethod()方法,使其不执行任何操作。如果我们想在方法被调用时抛出异常,可以使用doThrow()方法:
```
Mockito.doThrow(new RuntimeException()).when(mockObject).voidMethod();
```
这将模拟一个voidMethod()方法,使其在被调用时抛出RuntimeException异常。
Mockito.doReturn
Mockito.doReturn() is a method in the Mockito library that allows you to specify a return value for a method call on a mock object. It is used to stub a method call on a mock object to return a specific value, rather than executing the actual method code.
Here is an example of how to use Mockito.doReturn():
```
// Create a mock object of a class
SomeClass myMock = Mockito.mock(SomeClass.class);
// Stub the method call to return a specific value
Mockito.doReturn("hello").when(myMock).someMethod();
// Call the method on the mock object
String result = myMock.someMethod();
// Verify that the method was called and returned the correct value
assertEquals("hello", result);
```
In this example, we create a mock object of the SomeClass class and then use Mockito.doReturn() to stub the someMethod() method to return the string "hello". When we call someMethod() on the mock object, it will return "hello" instead of executing the actual method code. We then verify that the method was called and returned the correct value using the assertEquals() method.
阅读全文