gpt4 book ai didi

java - jUnit,Mockito。如何确保抽象类中的方法(模板方法)调用抽象钩子(Hook)方法?

转载 作者:行者123 更新时间:2023-12-02 11:50:09 28 4
gpt4 key购买 nike

我来了:

abstract class IdentifiedEntity<E extends IdentifiedEntity> implements Cloneable {
...
public void updateWith(E that) {
if (this != that) {
if (that.isNew()) {
throw new IllegalArgumentException("Cannot update with a new entity");
}
if (this.isNew()) {
throw new IllegalStateException("Cannot update a new entity");
}
if (this.getId() != that.getId()) {
throw new IllegalArgumentException("IDs do not match");
}
doUpdateWith(that);
}
}

abstract void doUpdateWith(E that);
...
}

public final class User extends IdentifiedEntity<User> {
...
@Override
void doUpdateWith(User that) {
assert that != null;
this.name = that.name;
this.email = that.email;
System.arraycopy(that.password, 0, password, 0, password.length);
this.enabled = that.enabled;
this.caloriesPerDayLimit = that.caloriesPerDayLimit;
}
...
}

问题是我如何对 updateWith(...) 进行单元测试,以确保它明确调用在后代中实现的抽象 doUpdateWith(...) (是的,当然,如果我通过了所有检查)?

就是你们!

最佳答案

创建一个虚拟子类

class ConcreteEntity extends IdentifiedEntity<ConcreteEntity> {
@Override
void doUpdateWith(ConcreteEntity that) {
}
}

然后像这样测试:

@Test
public void test() throws Exception {
ConcreteEntity e = Mockito.spy(new ConcreteEntity());
e.updateWith(e);

Mockito.verify(e).doUpdateWith(e);
}

不过这样的测试很特别。它不允许您更改方法的实现。

关于java - jUnit,Mockito。如何确保抽象类中的方法(模板方法)调用抽象钩子(Hook)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47936214/

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