最初,我的项目中几乎每个实体类都有一个转换器。我决定放弃所有这些转换器并创建一个将完成所有转换的 ConverterFactory。
@Service("dataConverterFactory")
public class DataConverterFactory implements ConverterFactory<String, CommonEntity> {
private static final Logger logger = LoggerFactory.getLogger(DataConverterFactory.class);
private final EntityManager em;
@Autowired
public DataConverterFactory(EntityManager em) {
this.em = em;
}
@Override
public <T extends CommonEntity> Converter<String, T> getConverter(Class<T> targetType) {
return new GenericConverter(targetType);
}
private final class GenericConverter<T extends CommonEntity> implements Converter<String, T> {
private final Class<T> targetType;
public GenericConverter(Class<T> targetType) {
this.targetType = targetType;
}
@Override
public T convert(String text) {
if (text != null && !text.isEmpty() && !text.equalsIgnoreCase("-1")) {//Ignore - to be determined later
try {
return (T) em.find(targetType, Integer.valueOf(text.trim()));
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
return null;
}
}
}
这工作正常,但我的测试在需要转换时失败。这是我的测试 xml 配置文件中的一个片段
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="dataConverterFactory"/>
</set>
</property>
</bean>
<bean id="dataConverterFactory" class="com.xyz.converter.DataConverterFactory"/>
样品测试
mockMvc.perform(fileUpload("/complaint/new")
.file(file)
.param("customer", "1")
)
在上面的测试中,我试图提交投诉,但它会失败,因为客户将为空。
参数 customer 应转换为扩展 CommonEntity 的类 Customer。
public class Complaint extends CommonEntity {
@NotNull
@ManyToOne
@JoinColumn(name = "customer_id", updatable = false)
private Customer customer;
}
模拟/设置转换服务如何在我的测试中工作?