1

i'm trying to use catch-exception library with JUnit4.

If i have a Service A:

@Service
public class A {

private Z delegate;

@Autowired
A(Z delegate){
    this.delegate = delegate;
}

@Transactional
public Integer testValue(String v) {
    return delegate.convertToInt(v);
}}

And a service Z:

@Service
public class Z {
   public Integer convertToInt(String v) {
    
    // some other method with spring-data
    
    return Integer.parseInt(v);
  }
}

And then the testclass:

@Configuration
@ComponentScan(basePackages = "prv.inv.api")
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class ExampleCatchExceptionTest {

@Autowired
A a;

@Test(expected = NumberFormatException.class) //OK
public void _1shouldThrowANumberFormatException(){
    a.testValue("a");
}

@Test  //KO Z service it's not injected by A
public void _2shouldThrowANumberFormatException(){
    catchException(a).testValue("a");
    assertTrue(caughtException() instanceof NumberFormatException);
}}

During the running of the integration-test the first pass but the second doesn't. It seems that spring doesn't inject the Z service, then if i remove the @Transactional from testValue method of A service now Z is injected correctly and the second test pass too. Any idea? Thank you

3lio11
  • 11
  • 2
  • Which Spring boot version? Why using JUnit 4 and not JUnit Jupiter aka JUnit 5 ? – khmarbaise Nov 20 '20 at 16:35
  • I use spring-boot 2.0.3, i think that junit4 it's not so old to ignore it, however i tried with spring-boot 2.4.0 and junit5 5.3.2 and jupiter 5.3.2 and no way the test doesn't pass. I have created a small example on gitlab: [https://gitlab.com/elion.haxhi/prv](https://gitlab.com/elion.haxhi/prv) , running clean install one test will fail. – 3lio11 Nov 21 '20 at 10:53
  • Really such an old version of Spring Boot. wow... JUnit 4 is old ... JUnit Jupiter is at 5.7.0 ... That the test don't pass has another reason... Ok. Found JDK 8... I would suggest to use [assertJ](https://assertj.github.io/doc/) to check for exceptions; I've created pull request to your repository to show how it looks like... Nothing to do with `@Transaction` .. cleaned up your pom / Code / etc. See my comments... – khmarbaise Nov 21 '20 at 16:33

0 Answers0