我在Spring Boot服务中使用了这个自定义转换器:
@Configuration
public class MongoConfig {
@Bean
public MongoCustomConversions customConversions(){
List<Converter<?,?>> converters = new ArrayList<>();
converters.add(ReferenceWriterConverter.INSTANCE);
return new MongoCustomConversions(converters);
}
@WritingConverter
enum ReferenceWriterConverter implements Converter<Reference, DBObject> {
INSTANCE;
@Override
public String convert(Reference reference) {
//do stuff
}
}
}
在我的控制器中,我正在使用MontoTemplate
与MongoDB进行交谈。因此,所有转换器都已加载到模板中。
但是,我想使用Spring注入功能来测试MongoDbTemplate
。我的意思是,我想使用应该已经加载的自定义转换器来测试MongoDbTemplate
。
关于如何实现它的任何想法?
编辑
public class ModelTest {
private List<Reference> references;
public ModelTest() {
this.references = new ArrayList<Reference>();
}
@Before
public void setUp() {
Reference reference = new Reference();
reference.setId("Ref1");
reference.setTimestamp(new Date());
Metadata met = new Metadata();
met.setId("Mdt1");
met.setUser("user");
met.setCreationTimestamp(new Date());
met.setMetadata("[{'departament': 'JUST'}]");
reference.setMetadata(met);
this.references.add(reference);
ServerAddress serverAddress = new ServerAddress("127.0.0.1", 27017);
MongoClient mongoClient = new MongoClient(serverAddress);
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "db");
mongoTemplate.insert(reference);
}
/**
* Assert Office mime type documents.
*/
@Test
public void office() {
fail("Not yet implemented");
}
}
编辑2
我也想使用自定义测试属性。我的意思是,目前,我们正在将属性设置为src/test/resources/application.properties
。
spring.data.mongodb.host: localhost
spring.data.mongodb.port: 27017
如何加载这些文件属性?
答案 0 :(得分:1)
解决方案1
如果要使用Spring上下文对其进行测试,则可以将Test类注释为SpringBootTest
并自动连接MongoTemplate
。然后,其中应包含您的自定义转化,以供您测试:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ModelTest {
private List<Reference> references;
@Autowired
private final MongoTemplate mongoTemplate;
public ModelTest() {
this.references = new ArrayList<Reference>();
}
@Before
public void setUp() {
Reference reference = new Reference();
reference.setId("Ref1");
reference.setTimestamp(new Date());
Metadata met = new Metadata();
met.setId("Mdt1");
met.setUser("user");
met.setCreationTimestamp(new Date());
met.setMetadata("[{'departament': 'JUST'}]");
reference.setMetadata(met);
this.references.add(reference);
mongoTemplate.insert(reference);
}
/**
* Assert Office mime type documents.
*/
@Test
public void office() {
fail("Not yet implemented");
}
}
解决方案2
如果您只想单独测试转换器,则可以像这样制作ReferenceWriterConverterTest
:
public class ReferenceWriterConverterTest {
private ReferenceWriterConverter converter;
@Before
public void setUp() {
converter = ReferenceWriterConverter.INSTANCE;
}
//test stuff
}