【发布时间】:2021-05-13 05:14:43
【问题描述】:
所以我是 junit 和 mockito 的新手。我决定我想尝试构建一个实际上已经完成了一些测试的 Spring Boot 项目。这是我目前所拥有的。
@ExtendWith(MockitoExtension.class)
class AccountServiceTest {
private AccountService accountService;
@Mock
private AccountRepository accountRepository;
@BeforeEach
void initServices(){
this.accountService = new AccountService(accountRepository);
}
@Test
@DisplayName("Get Account by Name 'Foo'")
void getAccountByName() {
assertNotNull(accountService);
//Create mocks
Account expected = new Account("2","Foo", "IT");
when(accountRepository.findByName("Foo")).thenReturn(Optional.of(expected));
Account actual = accountService.getAccountByName("Foo");
assertEquals(expected.getId(), actual.getId(), "Error, actual doesnt match expected");
}
}
现在这个测试通过了,但据我了解,我意识到我只是在输入我想要使用“when”函数调用出现的值。当我不知道实际服务是否会以这种方式运行时,模拟此功能的目的是什么?基本上我的理解是正确的,我正在提供我想要出现的值,或者服务实际上被调用并对我的数据库进行查询?此外,如果是这种情况,我将这些值提供给它,那么以这种方式进行测试有什么意义呢?
【问题讨论】:
标签: java spring-boot mockito junit5