I'm building a simple RESTful app (using Spark Java, although this question is more general).
The Handler below is called when the /users
index route is requested. It just queries for all users and renders an HTML template (using Velocity, but again this question is more general).
package com.example.api;
import java.util.*;
import spark.Request;
import spark.ModelAndView;
import spark.template.velocity.VelocityTemplateEngine;
public class UsersIndexHandler {
private Map<String, Object> locals;
private UserDao userDao;
public UsersIndexHandler(UserDao userDao) {
this.locals = new HashMap<>();
this.userDao = userDao;
}
public String execute(Request req, boolean formatAsHtml) {
// Set locals so they are available in the view
locals.put("users", userDao.all());
// Render the view
String body = new VelocityTemplateEngine().render(new ModelAndView(locals, "views/users/index.vm"))
return body;
}
}
I'm trying to write a basic Junit
test for this scenario. I could test the contents of the String
that's returned, but I have two issues with that -
The HTML for the page could be quite long, so it doesn't feel practical to do a direct comparison of the actual result with an expected test string
The content of view should be tested in a view test.
What's the "right" (generally accepted) way to test this? Is there a way to set expectations on VelocityTemplateEngine()
so we know that render()
is called correctly AND with correct arguments?
Or should I focus on just testing the locals
Map
object, even though I'd have to expose that to access it during tests?
Thanks!
I am in line with the views that Tom has mentioned in the comment but if still,
you want to follow this pattern, Powermockito (and plain Powermock also) have a way to do this. I will Just post an example here
Employee mockEmployeeObject = mock(Employee.class);
PowerMockito.whenNew(Employee.class)
.withAnyArguments().thenReturn(mockEmployeeObject);
verify(mockEmployeeObject, times(1)).someMethod();
Powermockito.whenNew(..) lets us return our mocked object when any new object of that class is created, since you want to verify the method parameters, it works well for you. You can add the verify that you need I just posted an example.
Hope this helps!
Good luck!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.