我正在学习Spring Core认证,我对单元测试与stubs的工作原理有一些疑问。使用存根的Spring JUnit测试究竟如何?
例如我有以下幻灯片:
所以,我认为,这意味着,在生产环境我有一个AuthenticatorImpl类使用JpaAccountRepo服务\库这是一个依赖关系它是 本身与一些依赖关系和生产环境(Spring,配置和数据库)有关。
所以,如果我想测试AuthenticatorImpl为单元我不得不删除链接到所有依赖。
所以使用stub的方式我必须创建一个存根,我想测试的单位先前的第一个依赖项。在这种情况下,它是JpaAccountRepo这样我就可以创建一个通用的AccountRepoStub这是一个假的实现不使用一个数据库,不使用特定的TECNOLOGY访问数据(我没有测试JpaAccountRepo所以我可以使用假实现,因为它是单元测试而不是集成测试)。
它是我的推理权,直到现在呢?
因此,举例来说,如果这是我的AuthenticatorImpl类
public class AuthenticatorImpl implements Authenticator {
private AccountRepository accountRepository;
public AuthenticatorImpl(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public boolean authenticate(String username, String password) {
Account account = accountRepository.getAccount(username);
return account.getPassword().equals(password);
}
}
正如你所看到的构造AuthenticatorImpl()构造采取AccountRepository对象paramether(即一个接口,而不是一个实现)。
所以我可以创建存根命名StubAccountRepository实现AccountRepository接口
class StubAccountRepository implements AccountRepository {
public Account getAccount(String user) {
return “lisa”.equals(user) ? new Account(“lisa”, “secret”) : null;
}
}
所以finnally我可以创建单元测试实现一个AuthenticatorImplTests类类
import org.junit.Before; import org.junit.Test; ...
public class AuthenticatorImplTests {
private AuthenticatorImpl authenticator;
@Before
public void setUp() {
authenticator = new AuthenticatorImpl(new StubAccountRepository());
}
@Test
public void successfulAuthentication() {
assertTrue(authenticator.authenticate(“lisa”, “secret”));
}
@Test
public void invalidPassword() {
assertFalse(authenticator.authenticate(“lisa”, “invalid”));
}
}
所以在我的setUp方法我建立一个AuthenticatorImpl对象将其传递给我的存根StubAccountRepository所以我删除具有依赖关系的链接,我只测试了AuthenticatorImpl单元。
这是对的还是我错过了什么?
Tnx