JUnit测试异步方法问题

参考案例:https://stackoverflow.com/questions/631598/how-to-use-junit-to-test-asynchronous-processes

通过注解@Async的异步方法,在Junit5测试时,数据一直保存不到mongodb数据库中

	@Async
	public CompletableFuture addUsers(List users) {
		Collection result = mongoTemplate.insertAll(users);
		return CompletableFuture.completedFuture(result.size());
	}

	@Async
	public CompletableFuture saveUser(User user) {
		User result = mongoTemplate.save(user);
		return CompletableFuture.completedFuture(result != null);
	}

原测试方法 

    @Test
    void testAddUsers() {
        List users = new ArrayList<>();
        users.add(new User(UUID.randomUUID().toString(), "55", "zhangsan", "1234"));
        users.add(new User(UUID.randomUUID().toString(), "77", "zhangsan", "1234"));
        mongoRepository.addUsers(users);
    }

 原测试结果

JUnit测试异步方法问题_第1张图片

数据库空空如也 

修改后方法

    @Test
    void testAddUsers() throws ExecutionException, InterruptedException {
        List users = new ArrayList<>();
        users.add(new User(UUID.randomUUID().toString(), "55", "zhangsan", "1234"));
        users.add(new User(UUID.randomUUID().toString(), "77", "zhangsan", "1234"));
        CompletableFuture future = mongoRepository.addUsers(users);
        assertEquals("2", String.valueOf(future.get()));
    }

 再进行测试结果

JUnit测试异步方法问题_第2张图片

数据库结果

JUnit测试异步方法问题_第3张图片

你可能感兴趣的:(junit,exception)