英文:
JMockit With Chain Methods
问题
我在理解如何正确使用Jmockit模拟链式方法方面遇到了困难。
这里是一个我想要测试的链式方法的示例:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().permitAll()
.and()
.httpBasic().disable()
.csrf().disable();
}
我目前的理解是需要手动指定Expectation中的每个方法并返回一个模拟对象。然后为每个步骤都这样做,就像下面这样:
new Expectations() {
http.authorizeRequest()
result = mockedRequests;
mockedRequests.anyRequest()
results = mockedAnyRequest;
// 等等
}
我的问题是,是否有更好的方法来做这个?我觉得这对于一个简单的测试来说是很多额外的代码。P.S 这是针对 JMockit 1.8 的。
英文:
I am having difficulty understanding how to properly mock chain methods with Jmockit
so here is an example of a chain method i would want to test
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().permitAll()
.and()
.httpBasic().disable()
.csrf().disable();
}
My undestanding currently is to manually specify each method in the Expectation and return a mock. Then do this for each step. Like below
new Expecations(){
http.authorizeRequest()
result = mockedRequests;
mockedRequest.anyRequest()
results = mockedAnyRequest;
//etc
}
My question is there a better way of doing this? I feel like this is alot of extra code for a simple test. P.S This is for JMockit 1.8
答案1
得分: 0
好的,以下是您要求的翻译内容:
好的,这里有一个简单的测试,它将对代码进行测试并为您提供完全覆盖。
@Test
public void testConfigure(
@Mocked final HttpSecurity http)
throws Exception
{
config.configure(http);
}
话虽如此,如果您需要执行更多像确认 'disable' 是否被调用,或者调用的顺序(从实现的角度来看很重要)等更奇特的操作,这个测试就无法(轻易地)完成。要达到这个目标,您最终会像您展示的那样在期望中构建这些链 - 非常麻烦。如果有人需要进行更高程度的测试,我认为那应该是更高级别的系统或集成测试的工作,而不是单元测试。
英文:
Well, here's a trivial test that will exercise the code and give you full coverage.
@Test
public void testConfigure(
@Mocked final HttpSecurity http)
throws Exception
{
config.configure(http);
}
That said, if you need to do more exotic stuff like confirm 'disable' was invoked, or the order of calls (which, implementation-wise, is important), this test cannot (easily) do. To go there, you wind up building those chains in the expectations like you were showing - PITA. If someone wanted such higher degree of testing, I'd argue that would be the job of a higher level system or integration test, not a unit test though.
专注分享java语言的经验与见解,让所有开发者获益!
评论