从简单开始并不断发展。
例如:假设我有一个实体 PendingOrder,我开始使用:
应用层:
@Transactional
@Override
public PendingOrder placeOrder(Address deliveryAddress, Date deliveryTime) {
PendingOrder pendingOrder = new PendingOrder(
pendingOrderRepository.nextTrackingId(), deliveryAddress,
deliveryTime); //by constructor
pendingOrderRepository.store(pendingOrder);
return pendingOrder;
}
后来当客户需要验证是否有可用的餐厅来接收送货信息时,我引入了 PendingOrderFactory 来强制执行一些域约束:
应用层:
@Transactional
@Override
public PendingOrder placeOrder(Address deliveryAddress, Date deliveryTime) {
PendingOrder pendingOrder = pendingOrderFactory.placeOrderWith(
deliveryAddress, deliveryTime);//refactor to factory
pendingOrderRepository.store(pendingOrder);
return pendingOrder;
}
领域层:
public PendingOrder placeOrderWith(Address deliveryAddress,
Date deliveryTime) {
if (restaurantRepository.isAvailableFor(deliveryAddress, deliveryTime)) {
return new PendingOrder(pendingOrderRepository.nextTrackingId(),
deliveryAddress, deliveryTime);
} else {
throw new NoAvailableRestaurantException(deliveryAddress,
deliveryTime);
}
}
另一方面,可以使用一些代码生成工具。这是我们在java中使用的
@ToString(of = "trackingId") //print PendingOrder.trackingId
@EqualsAndHashCode(of = "trackingId")//compare trackingId when Equals
public class PendingOrder {// this is an entity
@ToString //print all fields
@EqualsAndHashCode //compare all fields
@NoArgsConstructor
// @NoArgsConstructor for frameworks only
public class Address {// this is a value object
而且,我们只在必要时添加它们,通常,当您编写测试报告显式错误时需要@ToString,当您使用模拟编写测试时需要@EqualsAndHashCode。
例如:pendingOrderFactory 是一个 mock,我们验证它是使用给定参数(deliveryAddress,deliveryTime)调用的,mock 框架通过 Equals 进行检查,当我们未能满足预期时,会显示一个报告。模拟框架调用 ToString 来指示哪个对象打破了预期。
@Test
public void placesAPendingOrder() throws Exception {
final PendingOrder pendingOrder = new PendingOrderFixture().build();
final Address deliveryAddress = pendingOrder.getDeliveryAddress();
final Date deliveryTime = pendingOrder.getDeliveryTime();
context.checking(new Expectations() {
{
allowing(pendingOrderFactory).placeOrderWith(deliveryAddress,
deliveryTime);//need to implement equals
will(returnValue(pendingOrder));
oneOf(pendingOrderRepository).store(pendingOrder);//need to implement equals
}
});
PendingOrder order = target.placeOrder(deliveryAddress, deliveryTime);
assertThat(order, is(pendingOrder));
}
希望这对 Java 示例有所帮助和抱歉,因为我是 C# 白痴 :(