1

我有使用 java8 和响应式测试异步执行的存储库:

zadd的界面:

Observable<Long> zadd(K key, double score, V member);



 public class TargetClass()
{
..
     public void executeMethod(List<String> input) {
            input.forEach(item -> redisConnection.reactive().zadd(...).subscribe(
                    result -> log.info("Success")
                    error -> log.error("Failed...")
            ));
        }
..
}

我的junit测试代码:

@Test
public void testMethod() {
  TargetClass targetClass=new TargetClass();
    targetClass.executeMethod(Arrays.asList("input1", "input2", "input3"));

    //as you can see I must put here Thread.sleep in order to let my execution to finish before continue since we have dependency on it

    try {
        Thread.sleep(4000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    //continue with testing..

如何修改我的代码部分权限。Thread.sleep添加让异步方法代码发生的感觉不正确

谢谢,雷。

4

1 回答 1

1

如果我是你,我会executeMethod通过添加 2 个新参数来重载方法,一个参数是要执行的函数,success另一个是failure. 我会用新方法protected代替,public我会在我的单元测试中测试这个新方法而不是另一个。您的public方法可以使用 this 调用新方法executeMethod(input, result -> log.info("Success"), error -> log.error("Failed..."))。在我的单元测试中,我可以提供一种方法来获得这样的结果:

@Test
public void testMethod() {
    TargetClass targetClass = new TargetClass();
    AtomicBoolean success = new AtomicBoolean();
    synchronized (success) {
        targetClass.executeMethod(
            list, 
            result -> {
                synchronized (success) {
                    success.set(true);
                    success.notify();
                } 
            }, 
            error -> {
                synchronized (success) {
                    success.set(false);
                    success.notify();
                } 
            }
        );
        success.wait();
    }
    // The rest of your unit test here
}
于 2016-05-01T10:28:17.597 回答