mardi 3 mars 2015

Spring Junit testing with h2 - Table not found

I am trying to test one of my services and it suddenly fails with the following exception.


I am trying to figure out what is causing this exception to be thrown:



Caused by: org.h2.jdbc.JdbcSQLException: Table "XYZ" not found; SQL statement:
insert into xyz (id, xx_id, yy_id, order, path, place_id, primary) values (null, ?, ?, ?, ?, ?, ?) [42102-183]


Connection:



Creating new JDBC Driver Connection to [jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=false]


PersistenceContext used for testing:



@Configuration
public class PersistenceContext {

@Bean
public EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:sql/db-schema.sql")
.build();
}

}


db-schema.sql



CREATE TABLE xyz(
id int(11) NOT NULL,
xx_id int(11) NULL,
yy_id int(11) NULL,
path varchar(200) NOT NULL,
date_time_added datetime NOT NULL,
"order" int(11) DEFAULT NULL,
"primary" bit(1) DEFAULT NULL,
PRIMARY KEY (id),
CONSTRAINT fk_xx FOREIGN KEY (xx_id) REFERENCES xx (id) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT fk_yy FOREIGN KEY (yy_id) REFERENCES yy (id) ON DELETE NO ACTION ON UPDATE NO ACTION
);


The class where the error is thrown



private Image addXyzForXX(MultipartFile file, Xx xx) throws ... {
String destDir = resourceService.getPlacesUploadDir();
Xyz xyz = new Xyz();

xyz.setXx(xx);

String filePath = imageUploadService.upload(file, destDir);

java.util.Date dt = new java.util.Date();

java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String currentTime = sdf.format(dt);

xyz.setPath(filePath);
xyz.setDateTimeAdded(currentTime);

xyz.setOrder(1);
xyz.setPrimary(true);

xyz = xyzRepository.save(xyz);
return xyz;
}


Xyz Repository



@Repository
public interface XyzRepository extends PagingAndSortingRepository<Xyz, Long> {

}

@Entity
@Table(name = "xyz")
public class Xyz{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String path;
private String dateTimeAdded;
private Integer order;
private Boolean primary;

@ManyToOne(optional=true)
@JoinColumn(name = "xxId")
private Xx xx;

[getters and setters for each field]
}


The testing class



@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
public class ImageServiceTest {
@Autowired
private XyzService xyzService;
@Autowired
private XxService xxService;
@Test
public void testArgumentsNullity3() throws Exception {
XX xx = new XX("a", "b", "c", "d", "e");
xx= xxService.addXx(xx);
xyzService.addImage(XxService.Scope.XX, xx,new MockMultipartFile("a","a","image/jpeg", new byte[1024]));
}
}

Aucun commentaire:

Enregistrer un commentaire