简体   繁体   中英

AssertionError Unexpected method call when unit testing

I'm currently unit testing a method of my controller. Simply trying to test if the method returns the right string.

@RequestMapping(value = "/createTestscenario", method = RequestMethod.POST)
public String createTestscenario(@PathVariable("tdid") Integer testdesignID, @ModelAttribute("testscenario") Testscenario testscenario){

    Testdesign testdesign = this.testdesignService.getTestdesignById(testdesignID);
    testscenario.setTestdesign(testdesign);
    testdesign.getTestscenarioSet().add(testscenario);
    this.testdesignService.saveTestdesign(testdesign);

    return "redirect:/projects";
}

This is my unit test

@Test
public void createTestscenario1() throws Exception {

    Testdesign testdesign = new Testdesign();
    testdesign.setId(1);

    Testscenario testscenario = new Testscenario();
    testscenario.setId(1);
    Testscenario testscenario2 = new Testscenario();
    testscenario.setId(2);
    Set<Testscenario> set = new HashSet<>(Arrays.asList(testscenario));
    testdesign.setTestscenarioSet(set);
    testscenario.setTestdesign(testdesign);

    EasyMock.expect(testdesignService.getTestdesignById(1)).andReturn(testdesign);
    EasyMock.replay(testdesignService);

    String test = controller.createTestscenario(1, testscenario2);

    EasyMock.verify(testdesignService);

    Assert.assertEquals("redirect:/projects", test);
}

When I run the test i get the error:

java.lang.AssertionError: 
  Unexpected method call TestdesignServiceImpl.saveTestdesign(com.example.testclusters.model.Testdesign@28feb3fa):

I honestly don't know where the error lies. I can't Mock the saveTestdesign method like:

EasyMock.expect(testdesignService.save(testdesign)).andReturn(..);

Because save is a void method.

Does someone know how to fix this unit test?

Just call testdesignService.save(testdesign) before the replay. That's how you set exception of a void method.

You can also do

testdesignService.save(testdesign)
expectLastCall();

But the expectLastCall() is actually unnecessary. It exists solely to do things like expectLastCall().andThrow(new RuntimeException())

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM