13

テストSpringアプリケーションコンテキストをロードするテストクラスがあり、mongo dbでいくつかのテストデータをセットアップするjunitルールを作成したいと考えています。このために、ルール クラスを作成しました。

public class MongoRule<T> extends ExternalResource {

    private MongoOperations mongoOperations;
    private final String collectionName;
    private final String file;

    public MongoRule(MongoOperations mongoOperations, String file, String collectionName) {
        this.mongoOperations = mongoOperations;
        this.file = file;
        this.collectionName = collectionName;
    }

    @Override
    protected void before() throws Throwable {
        String entitiesStr = FileUtils.getFileAsString(file);
        List<T> entities = new ObjectMapper().readValue(entitiesStr, new TypeReference<List<T>>() {
        });
        entities.forEach((t) -> {            
            mongoOperations.save(t, collectionName);
        });
    }
}

現在、テスト クラス内でこのルールを使用し、mongoOperations Bean を渡しています。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringTestConfiguration.class)
public class TransactionResourceTest {

    @Autowired
    private ITransactionResource transactionResource;

    @Autowired
    private MongoOperations mongoOperations;

    @Rule
    public MongoRule<PaymentInstrument> paymentInstrumentMongoRule 
        = new MongoRule(mongoOperations, "paymentInstrument.js", "paymentInstrument");    
....
}

問題は、アプリケーション コンテキストが読み込まれる前に Rule が実行されるため、mongoOperations 参照が null として渡されることです。コンテキストがロードされた後にルールを実行する方法はありますか?

4

2 に答える 2

2

いくつかの抽象スーパークラスを使用したソリューションは次のとおりです。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringTestConfiguration.class)
public abstract class AbstractTransactionResourceTest<T> {

    @Autowired
    private ITransactionResource transactionResource;

    @Autowired
    private MongoOperations mongoOperations;

    @Before
    public void setUpDb() {
        String entitiesStr = FileUtils.getFileAsString(entityName() + ".js");
        List<T> entities = new ObjectMapper().readValue(entitiesStr, new TypeReference<List<T>>() {});
        entities.forEach((t) -> {            
            mongoOperations.save(t, entityName());
        }); 
    }    

    protected abstract String entityName();
}

それから

public class TransactionResourceTest extends AbstractTransactionResourceTest<PaymentInstrument> {
    @Override
    protected String entityName() {
        return "paymentInstrument";
    };

    // ...
}
于 2016-07-28T05:16:57.340 に答える