我有一个加载测试spring应用程序上下文的测试类,现在我想创建一个junit规则,它将在mongo db中设置一些测试数据。为此,我创建了一个规则类。
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 传递。有没有办法让规则在上下文加载后运行?