我有一个我要为其编写单元测试的类(我没有创建该类),并且我不确定如何仅测试一种方法。
该类(在此示例中为ShapeUtility)看起来像这样:
public ShapeUtility(ShapeConfig config) {
this.config = config;
}
public CircleDetails getDetails() {
CircleDetails cDetails = new CircleDetails();
//stuff
cDetails = getSize();
//stuff
return cDetails;
}
public CircleDetails getSize() {
CircleDetails cDetails = new CircleDetails();
//stuff
cDetails.setSize(size);
//stuff
return cDetails;
}
我在网上四处张望,并以此为例进行模拟:https://www.stevenschwenke.de/spyingWithMockito
我要为JUnit做的事情是这样的(因此,getSize
方法实际上并未在getDetails
方法中被调用):
ShapeConfig config = new ShapeConfig();
ShapeUtility utility = new ShapeUtility(config);
CircleDetails cDetails = spy(new CircleDetails());
when(cDetails.getSize().thenReturn(5));
utility.getDetails();
但是,cDetails
不会传递给ShapeUtility方法,因此无法正常工作。还有另一种方法吗?还是我应该研究重写代码,以便将CircleDetails对象传递给ShapeUtility方法?
答案 0 :(得分:2)
我相信您想在同一个类中模拟另一个方法的同时测试一种方法,这就是为什么您尝试使用部分模拟的原因。这是我为您的情况所建议的:
ShapeConfig config = mock(new ShapeConfig());
CircleDetails cDetails = mock(new CircleDetails());
ShapeUtility utility = new ShapeUtility(config);
// here is our spy
ShapeUtility spyUtility = spy(utility);
// here I assume that you have two getSize() methods, first in CircleDetails which returns number
// and second in ShapeUtility, which returns CircleDetails
when(cDetails.getSize().thenReturn(5));
when(spyUtility.getSize().thenReturn(cDetails));
// and then your assertion code
// assertThat(spyUtility.getDetails()...
希望这会有所帮助。