java – JMockit:如何在使用@Tested批注时调试测试?

问题
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 Google Group上的这个错误
was brought up

Yes, the problem is known, and already solved in JMockit 1.24.

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

点赞