I want to test my controller class and its methods.
My Controller method looks like this:
@RequestMapping(value = "/updateUserStory/{usid}", method = RequestMethod.GET)
public String updateUserStory(@PathVariable("trrid") Integer trrID, @PathVariable("usid") Integer userstoryID, Model model ){
UserStory userStory = this.userStoryService.getUserStoryById(userstoryID);
model.addAttribute("userstory", userStory);
model.addAttribute("trrID", trrID);
return "updateUserStory";
}
My test method looks like this:
public void updateUserStory() throws Exception {
Model model = mockModel();
UserStory userStory = new UserStory();
userStory.setId(1);
EasyMock.expect(userStoryService.getUserStoryById(1)).andReturn(userStory);
EasyMock.replay(userStoryService);
String test = controller.updateUserStory(1, 1, model );
EasyMock.verify(userStoryService);
Assert.assertEquals("updateUserStory", test);
}
I added @Mock
above for the userStoryService
@Mock
private UserStoryServiceImpl userStoryService;
and @TestSubject
for the UserStoryController
(In the test simply called controller).
@TestSubject
UserStoryController controller = new UserStoryController();
When running the test I keep getting A NullPointerException
at the EasyMock.expect
line. I don't know how this is failing. I am mocking the right method.
I see two possible reasons.
1. You haven't used any runner or rule.
To inject mocks, EasyMock needs a JUnit rule
@Rule
public EasyMockRule mocks = new EasyMockRule(this);
or a runner
@RunWith(EasyMockRunner.class)
public class MyTest {
2. The field type is UserStoryService
Not UserStoryServiceImpl
. So you should mock UserStoryService
instead.
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.