Spring Boot 测试:如何使用 AOP 部分模拟服务

问题描述

我正在尝试测试一个同时依赖于存储库和另一个服务的 Spring Boot 服务。我正在使用 TestContainers 来验证服务是否与存储库正确交互。但是,我需要模拟其他服务以提供将要使用的测试数据。有问题的服务方法需要是事务性的。

@Service
public class MyService {
  private MyRepository myRepository; // This needs to be a real repository
  private OtherService otherService; // This needs to be mocked

  @Autowired
  public MyService(MyRepository myRepository,OtherService otherService) {...}

  @Transactional
  public void methodTotest() {
    // Get (mock) data from otherService,and interact with (real) myRepository
  }
}

我可以通过手动创建服务及其依赖项来使其在我的测试中工作。但是,生成的对象只是一个 POJO,没有被 Spring 增强为 Transactional

@SpringBoottest
@ContextConfiguration(initializers = {TestContainersConfig.class})
public class MyServiceTest {
  @Autowired
  MyRepository myRepository;
  OtherService otherService;
  MyService myService;

  @BeforeEach
  void setup() {
    otherService = Mockito.mock(OtherService.class);
    // This works,except that the object is a POJO and so @Transactional doesn't work
    myService = new MyService(myRepository,otherService);
  }

  @Test
  @Transactional
  void testMethodTotest() {
    // Provide mock data
    when(otherSerivce.something()).thenReturn(...);

    // Run the test
    myService.methodTotest();

    // Would like to remove these lines: myService should already do it
    TestTransaction.flagForCommit();
    TestTransaction.end();

    // assertions...
  }
}

如何让 Spring 增强测试 MyService 实例,以便 methodToTest 处理事务?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)