TestNG + Spring 测试:EntityManager return null with testng

TestNG + Spring test: EntityManager return null with testng

我是 testng 框架的新手。从 junit 迁移到 testng 时,entityManager return 空值。它对我来说看起来很奇怪,谁能发现我的错误。在这里我把我的代码 snippets.thank 你 .

实体

@Entity
@Table(name = "school")
public class School {
    private Integer id;
    private String schoolName;
    private String address;

    getters and setters here
}

测试class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:/applicationContext.xml" })
@Transactional
public class SchoolTest {

@PersistenceContext
private EntityManager entityManager;

String address,schoolName; 


@BeforeClass
public void init() {
    address = "chinna kadai st";
    schoolName = "SVM School";
}
@Test
public void save_school() {
    School school = new School();
    school.setAddress(address);
    school.setSchoolName(schoolName);
    entityManager.persist(school);
}
}

以上代码在使用 Junit

时运行良好

而不是使用@RunWith(SpringJUnit4ClassRunner.class),你需要从AbstractTransactionalTestNGSpringContextTests

扩展你的测试class

阅读此处了解 Spring Reference docs 中的更多信息。