Spring Boot RabbitMQ Receiver JUnit测试在完成之前停止

时间:2019-04-28 13:05:44

标签: java spring-boot spring-data-jpa spring-rabbitmq

我有一个不明白的奇怪情况。

我有使用RabbitMQ的Spring Boot应用程序。当被JUnit测试调用时,它可以成功发送和接收消息。但是,当我尝试处理收到的消息(即使用收到的密钥查询数据库)时,它只会暂停。

问题

如何停止进程?

当我放置调试点时,它确实停止了,我可以看到photoEntity是从数据库中填充的,但是大约一秒钟后它退出了。我怀疑JUnit流程在服务可以完成之前已经完成。

例如,我得到以下控制台输出:

Received RabbitMQ msg = 3ade07c3-5f45-4aac-8054-0132bc85880b
about to get: photos... 3ade07c3-5f45-4aac-8054-0132bc85880b
got...
Received RabbitMQ msg = 3ade07c3-5f45-4aac-8054-0132bc85880b
about to get: photos... 3ade07c3-5f45-4aac-8054-0132bc85880b
got...

代码

接收器

@Component
public class RabbitMQReceiver {

    @Autowired
    private PhotoStatusProcessorService photoStatusProcessorService;

    @RabbitListener(queues = "${rabbitmq.queuename}")
    public void receive(UUID in) {
        System.out.println("Received RabbitMQ msg = " + in);
        photoStatusProcessorService.processPhotoForId(in);
    }
}

服务

@Component
public class PhotoStatusProcessorService {

    @Autowired
    private PhotoRepository photoRepository;

    public void processPhotoForId(UUID uuid) {
        System.out.println("about to get: photos... "+uuid);
        PhotoEntity photoEntity = photoRepository.getOne(uuid);
        System.out.println("got...");
        System.out.println("got: "+photoEntity);
        try {
            System.out.println("got: "+photoEntity);
            photoEntity.setStatus(PhotoStatus.processing);
            photoRepository.save(photoEntity);
            System.out.println("saved: "+photoEntity);
        } catch (Exception e) {
            photoEntity.setStatus(PhotoStatus.failed);
            photoRepository.save(photoEntity);
        }
    }
}

存储库

//@Repository
public interface PhotoRepository extends JpaRepository<PhotoEntity, UUID> {

}

RabbitMQ配置

@Configuration
public class RabbitMQConfig {

    ...
    @Profile("receiver")
    @Bean
    public RabbitMQReceiver receiver() {
        return new RabbitMQReceiver();
    }

    @Profile("sender")
    @Bean
    public RabbitMQSender sender() {
        return new RabbitMQSender();
    }
}

JUnit-测试将消息发送到队列,然后接收者接收它们并尝试处理每条消息,但是它停止了。该处理尝试更新存储库,但似乎尚未完成。就像测试已完成,才能完成对接收到的消息的处理。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = PhotoProcessorJavaApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles({"sender", "receiver"})
public class PhotoProcessorJavaApplicationTests {

@Test
public void testProcessPhotos() throws Exception {
    List<UUID> uuids = getAllUuids();
    HttpEntity<List<UUID>> entity = new HttpEntity<List<UUID>>(uuids, headers);
    ResponseEntity<String> response = restTemplate.exchange(
            createURLWithPort("/photos/process"),
            HttpMethod.POST, entity, String.class);
    System.out.println(response);
    assertEquals(200, response.getStatusCodeValue());
}

我是否需要向JUnit添加一些内容,例如另一个ActiveProfile用于服务?

0 个答案:

没有答案