gpt4 book ai didi

java - 如何在 "tell, don' 中进行单元测试并询问“追随者类?”

转载 作者:行者123 更新时间:2023-12-02 08:51:06 25 4
gpt4 key购买 nike

我认为这个问题最好用一个例子来解释。

public class MyService {
private OtherService theOther;
public void setTheOther(OtherService srv) { theOther = srv; }

public void myBusinessStuffFor(int id) {
theOther.applyToAllWith(id, new OtherService.Action() {
public void apply(Object whatever) {
doTheHardBusinessStuffWith(whatever);
}
}
}

private void doTheHardBusinessStuffWith(Object whatever) {
// here the business stuff provided by MyService
}
}

public interface OtherService {
void applyToAllWith(int id, Action action);

public interface Action {
void applyOn(Object whatever);
}
}

我喜欢这种模式,因为它非常有凝聚力。操作接口(interface)与其服务配对。许多类中的业务逻辑并不困惑。子类仅向操作提供数据,不必很忙。我从这里采用了它(http://jamesladdcode.com/?p=12)。问题是,如果我模拟 otherService,我没有找到一个好的解决方案来测试“doTheHardBusinessStuffWith(Object What)”方法中的行为。通过模拟,我必须关心如何调用业务方法。但我该怎么做呢。我使用mockito并已经用ArgumentCapture尝试过。但由于滥用 ArgumentCapture,感觉不太对劲。

我想知道类 MyService.myBusinessStuffFor(int id) 中使用的模式是否有名称(是策略模式)吗?但我的主要问题是如何使该代码可以通过模拟 OtherService 进行测试?

最佳答案

在这种情况下,其他服务并不是真正的业务服务。它唯一的职责是从给定的 ID 中查找对象,并对这些对象应用给定的操作。从功能上讲,这相当于以下代码:

Set<Object> objects = otherService.getObjectsWithId(id);
for (Object o : objects) {
doTheHardBusinessStuffWith(o);
}

使 doTheHardBusinessStuffWith 受到保护。为此方法创建单元测试。这是最重要的单元测试:测试业务逻辑。

如果你真的想对myBusinessStuffFor进行单元测试,你可以做的是创建一个模拟OtherService(我的意思是你自己实现这个模拟),它是由一组对象构建的,并将其给定的操作应用于集合中的所有对象。创建 MyService 的部分模拟,其中模拟了 doTheHardBusinessStuffWith 方法,并与模拟 OtherService 一起注入(inject)。在部分模拟上调用 myBusinessStuffFor,并验证是否已对对象集中的每个对象调用了 doTheHardBusinessStuffWith

关于java - 如何在 "tell, don' 中进行单元测试并询问“追随者类?”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8938531/

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