use*_*245 6 java junit mockito
我有一个这样的函数:
@Override
public ClassA createViewModel(ClassB product, ClassC classCVar)
throws ModuleException
{
ClassA classAVar = ClassA.builder().build();
try {
if (product != null && product.getProductData() != null) {
String gl_name = product.getProductData().offers().get(0).productCategory().asProductCategory()
.inlined().map(ProductCategory::glProductGroup).map(ProductCategory.GLProductGroup::symbol)
.orElse("");
classAVar.setName = gl_name;
}
return classAVar;
} catch (Exception e) {
// some lines of code.
}
Run Code Online (Sandbox Code Playgroud)
我这里有一行像 String gl_name =........... 其中包含一系列方法调用。现在我想使用 Mockito 模拟这个函数,并希望从所有这些函数调用中得到最终结果,就像 gl_name = "abc";
我怎样才能做到这一点?
我创建了一个新函数,并将方法调用链放入其中,如下所示:
public String fetchGLNameFunction(ClassB product)
{
String gl_name_result = product.getProductData().offers().get(0).productCategory().asProductCategory()
.inlined().map(ProductCategory::glProductGroup).map(ProductCategory.GLProductGroup::symbol)
.orElse("");
return gl_name_result;
}
Run Code Online (Sandbox Code Playgroud)
现在我尝试创建一个这样的模拟:
@Mock
private ClassA classAVar;
..........
............
@Test
public void testfunction1() throws Exception
{
when(classAVar.fetchGLNameFromAmazonAPI(classBVar)).thenReturn("abc");
Run Code Online (Sandbox Code Playgroud)
它仍然给我 NullPointerException 因为它正在执行我新创建的函数。
您Mockito需要定义模拟对象的行为。
// create mock
ClassB product = mock(ClassB.class);
// Define the other mocks from your chain:
// X, Y, Z, ...
// define return value for method getProductData()
when(product.getProductData()).thenReturn(X);
when(X.offers()).thenReturn(Y);
when(Y.get(0)()).thenReturn(Z); // And so on.... until the last mock object will return "abc"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10668 次 |
| 最近记录: |