Spring Data MongoDB:使用Fongo进行单元测试

时间:2016-04-25 18:28:40

标签: java spring mongodb unit-testing junit

我正在尝试使用Junit和Fongo测试mongo文档持久性。我能够将MongoTemplate注入要测试的类。但是调用mongotemplate.getCollection(" testCollection")返回null。我不知道如何为单元测试加载该集合。

要测试的课程: -

@Component
@Doc
public class MongoPersisterBean {

    @Autowired
    protected MongoTemplate template;

    @Override
    public boolean save(String collectionName, String json) {

      template.getCollection(collectionName).save(json);

      return true;
    }
}

Junit课程,

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MongoPersisterBeanTest {

    @InjectMocks
    private DocumentPersisterBean bean = new DocumentPersisterBean();

    @Mock
    @Autowired 
    private MongoTemplate mongoTemplate;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testSave() {

       System.out.println("Template "+mongoTemplate);

    System.out.println("Collection ===> "+mongoTemplate.getCollection("testCollection"));
    }

    @Configuration
    static class MongoTestConfiguration {

        @Bean
        public Mongo mongo() {
            // Configure a Fongo instance
            return new Fongo("mongo-test").getMongo();
        }

        @Bean
        public MongoTemplate mongoTemplate() {
            return new MongoTemplate(mongo(), "testDB");
        }

    }

0 个答案:

没有答案