catchException not working with @Transactional

69 views Asked by At

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

0

There are 0 answers