用于单元测试的Spring mongo db配置

时间:2015-09-17 09:42:28

标签: spring mongodb unit-testing spring-mvc

我尝试使用fongo进行单元测试,并在test中添加另一个mongo配置来替换原来的配置,但它不起作用。

我按照一些教程使用

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration

这两个注释用于测试类,我尝试了它,它失败了bean创建错误如下:

java.lang.IllegalStateException: Failed to load ApplicationContext
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class]
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling

这是我的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = Controller.class)
public class ApplicationTests {
  @Autowired
  private WebApplicationContext webApplicationContext;

  private MockMvc mockMvc;

  @Before
  public void setUp() throws Exception {
    mockMvc = webAppContextSetup(webApplicationContext).build();
  }

  ... Tests here ...

  @After
  public void tearDown() throws Exception {
  }

  @Configuration
  @EnableMongoRepositories
  @ComponentScan(basePackageClasses = { RecorderRepository.class })
  static class MongoConfiguration extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
      return "test-db";
    }

    @Override
    public Mongo mongo() {
      return new Fongo("test").getMongo();
    }

    @Override
    protected String getMappingBasePackage() {
      return "com.mongo.test";
    }
  }
}

我正在使用spring-data-mongodb:1.7.2.RELEASE并通过在我的应用程序中调用mongoOperation而不是自动装配存储库来访问db。喜欢这个

private AnnotationConfigApplicationContext context =
    new AnnotationConfigApplicationContext(MongoConfig.class);
private MongoOperations mongoOperation =
    (MongoOperations) context.getBean("mongoTemplate");

这就是

的原因
@ComponentScan(basePackageClasses = { RecorderRepository.class })

不工作?

我该怎么做让它有效?我将非常感谢您提供的任何帮助。

=============================================== ==============

更新

我试过嵌入式mongodb,仍然遇到了无法连接到数据库的问题。我需要设置其他任何东西吗?或者添加注释?

这是我的配置:

static class MongoConfiguration extends AbstractMongoConfiguration {
  private MongodStarter starter = MongodStarter.getDefaultInstance();

  @Override
  public Mongo mongo() throws Exception {
    return new MongoClient("localhost", 12345);
  }

  @Bean(destroyMethod = "stop")
  public MongodProcess mongod() throws IOException {
    return mongodExe().start();
  }

  @Bean(destroyMethod = "stop")
  public MongodExecutable mongodExe() throws IOException {
    return starter.prepare(mongodConfig());
  }

  @Bean
  public IMongodConfig mongodConfig() throws IOException {
    return new MongodConfigBuilder().version(Version.Main.PRODUCTION)
                                    .net(new Net(12345,Network.localhostIsIPv6()))
                                    .build();
  }
}

1 个答案:

答案 0 :(得分:0)

我从未使用过Fongo。我用Embedded Mongo做了这个。

    Session.sharedInstance.ApiManager().request(...

这适用于Spring Boot。启动嵌入式Mongo并设置import com.mongodb.Mongo; import com.mongodb.MongoClientOptions; import de.flapdoodle.embed.mongo.MongodExecutable; import de.flapdoodle.embed.mongo.MongodProcess; import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.IMongodConfig; import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; import de.flapdoodle.embed.mongo.config.Net; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.mongo.MongoProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.io.IOException; import static de.flapdoodle.embed.mongo.distribution.Version.Main.PRODUCTION; /** * Embedded MongoDB configuration for testing. * * @author Ken Blair */ @Configuration public class EmbeddedMongoConfig { @Autowired private MongoProperties properties; @Autowired(required = false) private MongoClientOptions options; @Bean(destroyMethod = "close") public Mongo mongo() throws IOException { final Net net = mongod().getConfig().net(); properties.setHost(net.getServerAddress().getHostName()); properties.setPort(net.getPort()); return properties.createMongoClient(options); } @Bean(destroyMethod = "stop") public MongodProcess mongod() throws IOException { return mongodExe().start(); } @Bean(destroyMethod = "stop") public MongodExecutable mongodExe() throws IOException { return MongodStarter.getDefaultInstance().prepare(mongodConfig()); } @Bean public IMongodConfig mongodConfig() throws IOException { return new MongodConfigBuilder().version(PRODUCTION).build(); } } 以连接到嵌入式实例。如果您没有使用Spring Boot,那么您需要更新负责mongo连接的任何配置,而不是更新MongoProperties