gpt4 book ai didi

java - 依赖注入(inject)如何使测试更容易——需要一个 Java 示例来理解这个概念吗?

转载 作者:行者123 更新时间:2023-12-03 22:57:29 25 4
gpt4 key购买 nike

所以我明白了什么是依赖注入(inject):

Instead of having your objects creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor or via property setters, and you make it somebody else's problem (an object further up the dependency graph, or a dependency injector that builds the dependency graph). A dependency as I understand here is any other object the current object needs to hold a reference to

太棒了。现在这如何使测试更容易?这是有道理的,但我正在努力想一个例子来巩固我脑海中的概念。您能否提供一个示例,说明测试代码变得比我们在类中硬连接依赖项更容易?

提前谢谢你。

最佳答案

让我们举个例子。假设您要测试雷管:

public class Detonator {
private Bomb bomb = new AtomicBomb();

public void pushButton() {
// do some stuff to test, and at the end
bomb.explode();
}
}

现在,你遇到了一个严重的问题,因为每次你想要测试雷管,你都会让炸弹爆炸,而这是非常昂贵的。所以你使用依赖注入(inject)来解决问题:

public class Detonator {
private Bomb bomb;

public Detonator(Bomb bomb) {
this.bomb = bomb;
}

public void pushButton() {
// do some stuff to test, and at the end
bomb.explode();
}
}

这对您的测试有何影响?一切,因为现在您可以通过这种方式测试雷管:

Bomb fakeBomb = new WaterBalloonBomb();
Detonator detonator = new Detonator(fakeBomb);
detonator.pushButton();
// test that the fake bomb has exploded

现在这是一个非常不现实的场景。但是只需将 Detonator 替换为 BankingService,将 Bomb 替换为 MainFrameDatabaseAccessor,您就会明白:需要一个填充的大型机数据库来测试服务的业务逻辑非常繁琐,使测试难以编写,执行起来也很慢。通过使用模拟框架,您可以创建注入(inject)类的动态实现,并验证此模拟对象的断言:

MainframeDatabaseAccessor mock = mock(MainFrameDatabaseAccessor.class);
when(mock.findAccount(id1)).thenReturn(sourceAccount);
when(mock.findAccount(id2)).thenReturn(destinationAccount);

BankingService service = new BankingService(mock);
service.transfer(id1, id2, 1000);
// now test that sourceAccount has lost 1000 dollars and destinationAccount has won 1000 dollars

verify(mock).logTransaction(any(Transaction.class));

关于java - 依赖注入(inject)如何使测试更容易——需要一个 Java 示例来理解这个概念吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23618509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com