想要在jUnit测试中访问延迟加载的集合时出现NullPointerException

时间:2014-02-15 10:34:14

标签: spring-mvc junit many-to-one

在我的Spring应用程序中,我有两个实体:

@Entity
public class Category {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
      ....
  @OneToOne
  @Cascade({CascadeType.ALL})
  @JoinColumn(name="page_id")
  private Page page;

  @OneToMany(fetch=FetchType.LAZY, mappedBy="category")
  private List<Shop> shop;

      ..getters and setters
 }

  @Entity
  public class Shop {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;
      ....

  @OneToOne(mappedBy="shop")
  private Settings settings;


  @ManyToOne
  @Cascade({CascadeType.SAVE_UPDATE})
  @JoinColumn(name = "category_id")
  private Category category;

  @OneToOne
  @Cascade({CascadeType.ALL})
  @JoinColumn(name = "page_id")
  private Page page;
      ...getters and setters

}

在我的测试中,jUnit我添加了一些类别和一些这个类别的商店,当我想访问商店列表当前类别我有一个错误     java.lang.NullPointerException ....

我的测试:

@ContextConfiguration(locations = {
    "classpath:security-context.xml",
    "classpath:dao-context.xml"
})
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@TransactionConfiguration(transactionManager="transactionManager", defaultRollback=false)
@Transactional
public class CategoryTest { 

Shop shop1 = new Shop(....);
Shop shop1 = new Shop(....);
Category category1 = new Category(....);
Category category2 = new Category(....);

@Test
public void someTest(){
    shop1.setCategory(category1);
    shop2.setCategory(category2);
    shopService.add(shop1);
    shopService.add(shop2);
    assertEquals(2, shopService.getAllShop().size());
    assertEquals(2, categoryService.getAllShop().size());
      //IN THIS LINE I HAVE A ERROR
    assertEquals(1, categoryService.getCategory(category1.getId()).getShop().size());
   }
 }

为了访问lazy atribute,我添加到我的web.xml文件:org.springframework.orm.hibernate3.support.OpenSessionInViewFilter这在前面的应用程序中正常工作,而不是在jUnit测试中。
哪一点我犯了错误?

1 个答案:

答案 0 :(得分:0)

当会话打开时,延迟加载仅在事务内部进行。因此,除非事先初始化延迟加载的集合,否则测试方法中将为null。

Another similar question