13

我有一个加载测试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 传递。有没有办法让规则在上下文加载后运行?

4

2 回答 2

4

据我所知,您无法以如此直接的方式实现您想要实现的目标,因为:

  1. 该规则在 Spring 的 Application Context 之前被实例化。
  2. SpringJUnit4ClassRunner 不会尝试在规则的实例上注入任何东西。

这里描述了一个替代方案:https ://blog.jayway.com/2014/12/07/junit-rule-spring-caches/但我认为它在可以加载到 mongodb 方面会有所不足。

为了实现您想要实现的目标,您可能需要一个测试执行侦听器,该侦听器将在您的规则对象上注入您需要的任何依赖项。

于 2017-02-22T17:58:56.753 回答
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 回答