2017-12-22 25 views
0

ここで私は行く:jUnit、Mockito。抽象クラス(templaeメソッド)でメソッドを保証する方法は、抽象的なフックメソッドを呼び出しますか?

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; 
    } 
    ... 
} 

質問は(はい、確かに、私がチェックしSALL tpasse場合)、それはdefinely子孫にimplmented抽象doUpdateWith(...)を呼び出すことを確認するために、どのようにすることができます私のユニットテストupdateWith(...)のですか?

あなたよね!このようなテストは非常に特別であるしかし

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

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

答えて

0

@CoronAの助けを借りて、私は答えを見つけました。ここにあります:

@Test 
public void updateWith() { 
    User user = this.user.clone().setId(100); 
    User mock = Mockito.spy(user); 
    mock.updateWith(user); 
    Mockito.verify(mock).doUpdateWith(user); 
} 

ありがとう皆さん!

+0

それが役に立ったら、私の答えを受け入れるよりも親切だっただろう;)。 – CoronA

+0

@CaronAはい、そうです – danissimo

1

は次のようにテストし、その後

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

ダミーサブクラスを作成します。メソッドの実装を変更することはできません。

+0

原則は健全ですが、この方法では動作しません。「検証」はムービーインスタンスでのみ機能します。ダミーのサブクラスは、メソッドが呼び出される頻度を表すカウンタを保持する必要があります。 – daniu

+0

これらのスニペットは単なるアイデアではなく、実際に動作します。自分で試してみてください。 'IndentifiedEntity'がupdateを呼び出さないと失敗し、updateを呼び出すと成功します。 – CoronA

+0

ああ、私は 'Mockito.spy'を見逃していましたが、これは実際これに関する重要なビットです。実際には、これであなたは具体的なクラスを必要としません。あなたは単に 'sut = Mockito.spy(IdentifiedEntity.class)を実行することができます。 sut.updateWith(sut); .doUpdateWith(sut); 'を確認してください。 – daniu

関連する問題