```xml
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.3.1</version>
<scope>test</scope>
</dependency>
```
```java
import static org.mockito.Mockito.*;
public class CalculatorTest {
@Test
public void testAddition() {
// 建立 Calculator 的 mock 物件
Calculator calculator = mock(Calculator.class);
// 設定當呼叫 calculator.add(2, 3) 時,回傳 5
when(calculator.add(2, 3)).thenReturn(5);
// 測試
int result = calculator.add(2, 3);
assertEquals(5, result);
// 確認方法是否有被呼叫
verify(calculator).add(2, 3);
}
}
```
### MockitoJUnitRunner
```java
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@Mock
private MyRepository repository;
@InjectMocks
private MyService service;
@Test
public void testMyService() {
when(repository.findById(1L)).thenReturn(new MyEntity());
MyEntity result = service.findById(1L);
assertNotNull(result);
}
}
```