catchexception不使用@transactional

scyqe7ek  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(308)

我正在尝试对junit4使用catch异常库。
如果我有服务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);
}}

和服务z:

@Service
public class Z {
   public Integer convertToInt(String v) {

    // some other method with spring-data

    return Integer.parseInt(v);
  }
}

然后是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);
}}

在集成测试的运行过程中,第一次通过,但第二次没有。似乎spring没有注入z服务,那么如果我从一个服务的testvalue方法中删除@transactional,那么现在z被正确注入,第二个测试也通过了。你知道吗?谢谢您

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题