2

I have following code:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TRConfig.class)
public class ARepositoryTest {

    @Autowired
    ARepository aRepository;

    private A a = new A("value");

    @Before
    public void setup() {
        aRepository.save(a);
    }

    @Test
    public void findByValue1() {
        assertEquals(a, aRepository.findByValue("value"));
    }

    @Test
    public void findByValue2() {
        assertEquals(null, aRepository.findByValue("inv"));
    }
}

I have following error on second test, I don't know if first passes because second is the first one which runs:

org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find ...model.a.A with id 10; nested exception is javax.persistence.EntityNotFoundException: Unable to find model.a.A with id 10

But when I do it like this, the test passes:

@Test
    public void findByValue() {
         assertEquals(a, aRepository.findByValue("value"));
         assertEquals(null, aRepository.findByValue("inv"));
    }

Why? What I have to do to make it running properly?

Here is my config:

@EnableAutoConfiguration
@EnableJpaRepositories(basePackageClasses = ARepository.class)
@EntityScan(basePackageClasses = A.class)
@Import({ DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class })
public class TRConfig {
}
1kka
  • 77
  • 11
  • Try to add `@Transactional` on `ARepositoryTest`. – Ali Dehghani Apr 14 '16 at 14:24
  • Done, still doesn't work – 1kka Apr 14 '16 at 14:27
  • 1
    Well, I have no clue about Spring; but I am wondering: could the problem be that your atBefore ... runs twice when you have two tests, but only once, when they within the same test? Guess what I am saying is: have you tried to move that statement from atBefore ... directly in your test method; and run it twice there? – GhostCat Apr 14 '16 at 14:29
  • Or you should add an (at)After to clear your repository, as you will add another record with each test you execute. – Uwe Allner Apr 14 '16 at 14:40
  • Show us the implementation of ARepository, or make sure you understand the code that actually interacts with the JPA EntityManager. In JPA, there is a difference between 'getting' and 'finding'. Getting will throw exceptions when the object does not exist. Find will return null. You need to figure out which one is used within ARepository. – Hans Westerbeek Apr 14 '16 at 15:40
  • 1
    This doesn't look like a testing problem, but rather with how spring data handles failed lookups. This related question suggests that *by design* the lookup failure is sometimes delayed, which looks exactly like the issue you're having: http://stackoverflow.com/questions/32264758/why-does-getone-on-a-spring-data-repository-not-throw-an-entitynotfoundexcept – blgt Apr 14 '16 at 15:55

0 Answers0