在其他类

时间:2015-10-26 12:47:46

标签: java junit mockito

public class aClass {
   public String meth1() {
      bClass b = new bClass();
      b.meth2();// I don't want to call this method
      //buss logic
   }
}

public class bClass {
   public String meth2() {
      // some logic
   } 
}

目前我正在为aClass中的meth1创建一个JUnit测试用例。但是,我不想在meth2中调用bClass,只需执行aClass中的busslogic即可。课程aClassbClass已修复 - 我无法更改其代码。

我使用Mockito和PowerMock尝试了许多内容,例如@InjectMocksdoNothing,但在meth2中调用meth1时始终会调用aClass。我该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

PowerMock拯救:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ aClass.class })
public class TestPowerMock {

    @Test
    public void shouldBlaBla() throws Exception {
        // you can do whatever you want on bMock, because it's a mock
        bClass bMock = PowerMockito.mock(bClass.class);
        // when aClass instantiates bClass, the mock will be returned
        PowerMockito.whenNew(bClass.class).withNoArguments().thenReturn(bMock);
        // your test
        aClass a = new aClass();
        a.meth1();
    }
}

了解更多here