【问题标题】:Method invocation exception when using spring mvc test使用spring mvc测试时方法调用异常
【发布时间】:2018-08-14 19:21:00
【问题描述】:

我定义了一个 @RestController 用于将 Person 类更新为:

@RestController
@RequestMapping("/api/person")
class PersonRestController {

    @Autowired
    private IPersonService mPersonService;

    @PostMapping("/update")
    public Person updatePerson(@RequestBody Person person) {
        Optional<Person> personIfExists = mPersonService.findOneIfExists(person.id);
        if (!personIfExists.isPresent()) {
            throw new IllegalArgumentException();
        }
        return mPersonService.update(personIfExists.get());
    }
}

为简洁起见,我们假设存在IPersonService 及其正确实现。该实现标有@Service,位于spring boot 组件扫描路径上。我正在使用JMockitTestNGSpring MVC Test 框架来测试这个控制器。我还使用GSONPerson 对象转换为JSON。这是我的测试方法:

@Test
    public void testUpdateFileDetails() throws Exception {
        Person person = new Person();
        person.id = "P01";
        person.name = "SOME_PERSON_NAME";
        person.age = 99;

        new Expectations() {{
            mockedPersonService.findOneIfExists("P01");
            result = new IllegalArgumentException();
        }};

        String personJson = new Gson().toJson(person);

        mvc.perform(post("/api/person/update").content(personJson))
                .andExpect(status().is4xxClientError());
    }

当我运行这个测试用例时,我不断收到以下异常:

Missing 1 invocation to:
        com.mytestapplication.services.api.IPersonService#getFileDetails("P01")
        on mock instance: com.mytestapplication.services.api.$Impl_IPersonServcie@8c11eee

        Caused by: Missing invocations
        at com.mytestapplication.rest.api.PersonRestControllerTest$2.<init>(PersonRestControllerTest.java:<line_number>)
        at com.mytestapplication.rest.api.PersonRestControllerTest.testUpdatePerson(PersonRestControllerTest.java:<line_number>)

这里指的是包含语句的行:new Expectations() {{ ... }}

您能帮我找出这个异常的原因吗?

【问题讨论】:

    标签: java spring-boot testng jmockit spring-mvc-test


    【解决方案1】:

    看来你需要为方法调用提供模拟

    mPersonService.update(personIfExists.get());

    这是你的控制器方法的返回语句。

    我也相信该方法在服务中还有另一个方法调用 getFileDetails。

    因此,如果为这两个方法调用提供模拟,您的测试应该可以工作。

    【讨论】:

    • 好的。但在我的回答中,我要求模拟 IPersonServive 的方法调用。尝试为方法调用 mPersonService.update 和 personIfExist.get() 提供模拟
    猜你喜欢
    • 2013-05-16
    • 2018-11-18
    • 2013-08-11
    • 2023-03-07
    • 2012-09-11
    • 2017-07-12
    • 2021-10-01
    • 2015-04-04
    • 1970-01-01
    相关资源
    最近更新 更多