【问题标题】:JMockit: How to debug tests when using the @Tested annotation?JMockit:使用@Tested 注解时如何调试测试?
【发布时间】:2023-04-03 12:21:01
【问题描述】:

Debug Partial Mock in JMockit 和 Debugging Java code tested with Spock and JMockit 的问题已经解决了这个问题,即当 JMockit 重新定义/检测类时,被测软件 (SUT) 中的断点会被忽略。 推荐的解决方案是,一旦执行在您的测试类中停止,您应该在测试类中添加一个额外的断点,以便重新激活 SUT 中的断点。

但是,如果您在测试类中使用 @Tested 注释,则此解决方案不起作用,因为在这种情况下,测试类本身中的断点会被忽略。
这是一个例子:

package de.playground;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import mockit.Expectations;
import mockit.Injectable;
import mockit.integration.junit4.JMockit;

@RunWith(JMockit.class)
public class DebuggingWithJMockitTest {

    public interface Collaborator {
        String execute(String... args);
    }

    public static class ToTest {
        private Collaborator collaborator;

        public ToTest(Collaborator collaborator) {
            this.collaborator = collaborator;
        }

        public String doSomething() {
            return collaborator.execute("a", "b");
        }
    }


    @Injectable
    private Collaborator collaborator;

    @Tested
    private ToTest toTest;    

    @Test
    public void testHoldOnBreakpoint() {
        new Expectations() {{
                collaborator.execute((String[]) any); result = "whatever";
            }};

        String result = toTest.doSomething(); // add breakpoint here
        assertThat(result, is("whatever"));
    }
}

在这种情况下,调试器不会在String result = toTest.doSomething(); 行中停止。如果您不使用 @Tested 注释并在 @Before 方法中初始化 SUT,如下所示:

    // @Tested is not used
    private ToTest toTest;

    @Before
    public void before() {
        toTest = new ToTest(collaborator);
    }

断点工作得很好。

即使您在测试类中使用@Testedannotation,是否有任何解决方法可以调试您的代码?

【问题讨论】:

  • 还不知道,但是 JMockit 1.22 和 1.23 之间发生了一些变化,这导致了这种情况......我会为此打开一个问题。
  • 我发现了它现在发生的原因:JMockit 1.23 添加了对 JDK 9 的支持,这要求它使用Instrumentation#retransformClasses(...) 作为获取测试或测试类的字节码的一种方式。问题是,由于 JVM 限制,类重新定义/重新转换会导致所述类上的所有当前断点被删除。
  • 我可以确认测试类中的断点仍然适用于 1.22 版,但不适用于 1.23 版。如果我有时间,我会尝试再深入一点。也许有一些解决方法可以在重新定义类后重置断点......

标签: java unit-testing debugging jmockit


【解决方案1】:

JMockit Google Group 上的这个错误 was brought up:

是的,这个问题是已知的,并且已经在 J​​Mockit 1.24 中解决了。

看起来没有为它记录的问题。我们的团队在 JMockit 1.23 上遇到了这个问题,并且确实能够通过升级到 JMockit 1.24 来克服它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    相关资源
    最近更新 更多