我有一個測試類加載了一個測試spring應用程序上下文,現在我想創建一個junit規則,它將在mongo db中設置一些測試數據。爲此,我創建了一個規則類。使用spring bean的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豆。
@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");
....
}
問題是規則在應用程序上下文被加載之前得到執行,所以mongoOperations引用被傳遞爲null。在上下文加載後有沒有辦法讓規則運行?