import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@Mock
private MyRepository myRepository;
private MyService myService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
myService = new MyService(myRepository);
}
@Test
public void testQueryPage() {
// 设置模拟的返回数据,包含name和class字段
PageRows<VO> mockPageRows = new PageRows<>();
List<VO> mockDataList = Arrays.asList(
new VO("John", "Class A"),
new VO("Alice", "Class B")
);
mockPageRows.setRows(mockDataList);
when(myRepository.queryPage(anyInt(), anyInt())).thenReturn(mockPageRows);
// 调用被测试的方法
PageRows<VO> result = myService.queryPage(1, 10);
// 验证方法调用和结果
verify(myRepository).queryPage(1, 10);
assertEquals(mockPageRows, result);
}
}
在这个示例中,我们使用 @Mock
注解创建了一个模拟的 MyRepository
实例,并将其注入到 MyService
中。然后,在 testQueryPage
方法中,我们设置模拟的返回数据,使用 when
和 thenReturn
来指定 queryPage
方法的行为。最后,我们调用 myService.queryPage(1, 10)
来测试方法,然后使用 verify
来验证方法是否按预期调用,并使用 assertEquals
来验证返回的结果是否正确。