### Question:
MongoDbRegionWidgetRepository implements RegionWidgetRepository { @Override public RegionWidget save(RegionWidget item) { return item.getId() == null ? addNewRegionWidget(item) : updateRegionWidget(item); }  @Override Class<? extends RegionWidget> getType(); @Override RegionWidget get(String id); @Override RegionWidget save(RegionWidget item); @Override void delete(RegionWidget item); @Override List<RegionWidget> getAll(); @Override List<RegionWidget> getLimitedList(int offset, int pageSize); @Override int getCountAll(); void setTemplate(MongoPageOperations template);  }### Answer:
@Test public void save_Id_Valid() { RegionWidgetImpl widget = new RegionWidgetImpl(); RegionWidgetImpl replaced = new RegionWidgetImpl(); String id = "123"; widget.setId(id); replaced.setId(id); replaced.setCollapsed(true); Page parent = new PageImpl(); Region region = new RegionImpl(); List<Region> regions = new ArrayList<Region>(); regions.add(region); List<RegionWidget> regionWidgets = new ArrayList<RegionWidget>(); regionWidgets.add(replaced); parent.setRegions(regions); region.setRegionWidgets(regionWidgets); expect(template.findOne(getQuery(id))).andReturn(parent); expect(template.save(parent)).andReturn(parent); replay(template); RegionWidget savedWidget = widgetRepository.save(widget); assertTrue(region.getRegionWidgets().contains(widget)); assertFalse(region.getRegionWidgets().contains(replaced)); assertThat(savedWidget, is(sameInstance((RegionWidget)widget))); }
@Test public void save_Id_Valid_Page_Null() { RegionWidgetImpl item = new RegionWidgetImpl(); String id = "123"; item.setId(id); Page page = new PageImpl(); page.setRegions(new ArrayList<Region>()); expect(template.findOne(getQuery(id))).andReturn(page); replay(template); thrown.expect(IllegalStateException.class); thrown.expectMessage("Widget does not exist in parent page regions"); widgetRepository.save(item); }
@Test public void save_Id_Null_Page_Null_Region_Null() { RegionWidget widget = new RegionWidgetImpl(); thrown.expect(IllegalStateException.class); thrown.expectMessage("Unable to find page for region"); widgetRepository.save(widget); }
@Test public void save_Id_Null_Page_Null_Region_Valid_Page_Null() { RegionWidget widget = new RegionWidgetImpl(); Region region = new RegionImpl(); widget.setRegion(region); thrown.expect(IllegalStateException.class); thrown.expectMessage("Unable to find page for region"); widgetRepository.save(widget); }
@Test public void save_Id_Null_Page_Null_Region_Valid_Page_Valid_Id_Null() { RegionWidget widget = new RegionWidgetImpl(); Region region = new RegionImpl(); widget.setRegion(region); Page page = new PageImpl(); region.setPage(page); thrown.expect(IllegalStateException.class); thrown.expectMessage("Unable to find page for region"); widgetRepository.save(widget); }