我有一個要求,我想模擬從私有方法回傳的物件。我在我的專案中使用 junit 和 mockito。我無法在此處粘貼實際代碼,但示例代碼將如下所示。這里的限制是代碼是遺留代碼,我現在無法重構
測驗類
public class TestService {
public String test() {
TestDao testDao = getDaoObject();
int num = testDao.getData();
if (num < 10) {
return "hey you loose";
} else {
return "hey you win";
}
}
private TestDao getDaoObject() {
return new TestDao();
}
}
道類
public class TestDao {
public int getData() {
return 5;
}
}
測驗班
public class JUnitServiceTestExample {
@Test
public void test() {
TestDao testDao = Mockito.mock(TestDao.class);
TestService test = new TestService();
when(testDao.getData()).thenReturn(20);
assertEquals(test.test(), "hey you win");
}
}
請幫忙
uj5u.com熱心網友回復:
getDaoObject您可以將from稍微修改private為package-private如下所示:
TestDao getDaoObject() {
return new TestDao();
}
然后使用Mockito.spy(new TestService())stubgetDaoObject()并回傳你的 mocked testDao。
public class JUnitServiceTestExample {
@Test
public void test() {
TestDao testDao = Mockito.mock(TestDao.class);
TestService test = Mockito.spy(new TestService());
when(testDao.getData()).thenReturn(20);
doReturn(testDao).when(test).getDaoObject();
String result = test.test();
assertEquals("hey you win", result);
}
}
給你一個提示:正確使用assertEqualsis assertEquals(expected, actual)notassertEquals(actual, expected)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/466525.html
上一篇:com.typesafe.config.ConfigException$Missing:reference.conf:未找到鍵“默認”的配置設定
下一篇:將字串連接到Java流的所有元素
