jUnit 改变一个方法的行为

jUnit change behavior of a method

我必须对某些方法进行一些 jUnit 测试,而且我无法更改源代码。是否有可能在不更改源代码的情况下更改函数的行为? 看一个简单的例子:Class A 和 B 是源代码(无法更改)。当我在 Junit 测试中通过 testing() 在 B 中调用它时,我想从 A 更改 运行() 方法的行为。有什么想法吗?

public class A {
    public String run(){
        return "test";
    } 
}

public class B {
    public void testing() {
        String fromA = new A().run(); //I want a mocked result here
        System.out.println(fromA);
    }
}

public class C {
    @Test
    public void jUnitTest() {
        new B().testing();
        // And here i want to call testing method from B but with a "mock return" from run()         
    }
}

您无法按照自己的方式进行测试而不更改源代码。您不能模拟局部变量。我建议您向 B.class 添加新方法,它将 return new A()spy 使用 Mockito.

@Test
public void test(){
    final B spy = Mockito.spy(new B());    
    Mockito.doReturn(new C()).when(spy).getA();
} 

class C extends A {
    @Override
    public String run(){return "new String";}
}

在测试中使用字节码库不是一个好主意。

您可以使用 Mockito and PowerMock:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest(B.class)
public class C {
    @Before
    public void setUp() throws Exception {
        A a = spy(new A());
        when(a.run()).thenReturn("mock return");
        PowerMockito.whenNew(A.class).withNoArguments().thenReturn(a);
    }

    @Test
    public void jUnitTest() {
        new B().testing();
    }
}