使用spring bean的JUnit规则

时间:2016-07-28 04:34:25

标签: java junit spring-junit

我有一个加载测试弹簧应用程序上下文的测试类,现在我想创建一个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传递。有没有办法在加载上下文后运行规则?

2 个答案:

答案 0 :(得分:4)

据我所知,你想要实现的目标是不可能的,因为:

  1. 规则在Spring的应用程序上下文之前实例化。
  2. SpringJUnit4ClassRunner不会尝试在规则的实例上注入任何内容。
  3. 这里有一个替代方案:https://blog.jayway.com/2014/12/07/junit-rule-spring-caches/但是我认为它可能无法加载到mongodb中。

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

答案 1 :(得分:1)

这是一个解决方案,使用一些抽象的超类:

@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";
    };

    // ...
}