我们可以使用Mockito为实现存储库调用的方法编写测试吗?例如,下面的方法是使用命名查询从书库中获取电子书 -
public RepositoryItem[] getEBooks(DynamoHttpServletRequest request) {
RepositoryItem[] results = null;
Repository rep = (Repository) request.resolveName("/atg/products/BookRepository");
try {
RepositoryItemDescriptor desc = rep.getItemDescriptor("Book");
RepositoryView view = desc.getRepositoryView();
if (view instanceof NamedQueryView) {
NamedQueryView nameView = (NamedQueryView) view;
ParameterSupportView pSupportView = (ParameterSupportView) view;
String queryName = "GetBooks";
Query namedQuery = nameView.getNamedQuery(queryName);
Object[] params = { "ebook" }; //book type
results = pSupportView.executeQuery(namedQuery, params);
}
} catch (RepositoryException e) {
logError(e.getMessage());
}
return results;
}
感谢。
答案 0 :(得分:4)
是的,你可以。问题是你在这个例子中测试你的代码还是ATG?
假设您的上述方法包含在名为GetBooks
的类中,您的测试可能如下所示:
@InjectMocks private GetBooks testObj;
@Mock private DynamoHttpServletRequest requestMock;
@Mock private Repository bookRepositoryMock;
@Mock private RepositoryItemDescriptor bookRepositoryItemDescriptorMock;
@Mock private GSAView bookRepositoryViewMock; //The only oddity here but GSAView is the common denominator for NamedQueryView and ParameterSupportView
@Mock private Query namedQueryMock;
@Mock private RepositoryItem resultRepositoryItem1, resultRepositoryItem2;
@BeforeMethod(groups = { "unit" })
public void setup() throws Exception {
testObj = new GetBooks();
MockitoAnnotations.initMocks(this);
Mockito.when(requestMock.resolveName("/atg/products/BookRepository")).thenReturn(bookRepositoryMock);
Mockito.when(bookRepositoryMock.getItemDescriptor("Book")).thenReturn(bookRepositoryItemDescriptorMock);
Mockito.when(bookRepositoryItemDescriptorMock.getRepositoryView()).thenReturn(bookRepositoryViewMock);
Mockito.when(bookRepositoryViewMock.getNamedQuery("GetBooks")).thenReturn(namedQueryMock);
List<RepositoryItem> resultArrayList = new ArrayList<RepositoryItem>();
resultArrayList.add(resultRepositoryItem1);
resultArrayList.add(resultRepositoryItem2);
Object[] params = { "ebook" }; //It may be simpler to test if this was a constant
Mockito.when(bookRepositoryViewMock.executeQuery(namedQueryMock, params)).thenReturn(resultArrayList.toArray(new RepositoryItem[resultArrayList.size()]));
}
@Test(groups = { "unit" })
public void testGetEBooks()throws Exception{
RepositoryItem[] result = testObj.getEBooks(requestMock);
Assert.assertTrue(result.length == 2); //What do you want to test?
}
当通过greenbar
执行时,这会给出TestNG
。但是你在这里测试的是什么?
单独说明。您应该更多地使用(protected
)常量,因为您可以在Mockito
测试的包范围内使用它们。