gpt4 book ai didi

java - 无法为 Junit 的方法创建模拟调用

转载 作者:行者123 更新时间:2023-12-01 21:47:53 26 4
gpt4 key购买 nike

嗨,我是 Junit 和 Mockito 的新手,所以请原谅我犯的一些误解/错误。我有一个 springbott 服务,我想测试它,我想模拟一个方法调用,该方法调用是在我正在测试的方法之一中进行的,但由于某种原因它不起作用。我使用了 when(xxx.method(anyArgs)).return(someData) 以及 doReturn(someData).when(xxx).method(anyArgs); 但是我仍然收到相同类型的错误:InvalidUseOfMatchersException。我模拟了服务层,但我无法弄清楚导致问题的原因。

确切的堆栈跟踪:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced or misused argument matcher detected here:

-> at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))

This message may appear after an NullPointerException if the last matcher is returning an object
like any() but the stubbed method signature expect a primitive argument, in this case,
use primitive alternatives.
when(mock.get(any())); // bad use, will raise NPE
when(mock.get(anyInt())); // correct usage use

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.


at service.EventServiceTestUnit.validatePostDataTest(EventServiceTestUnit.java:61)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:79)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:85)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

我的服务层代码:

// imports here

@Service
@AllArgsConstructor
public class EventServiceImpl implements EventService {

private EventModelRepo eventModelRepo;

static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

// methods that dont matter


public int createAPost(EventDetails eventDetails) {
//Some where here the isOwner(STRING) is called
}

public static void getRequest(String reqUrl) throws IOException {
GenericUrl url = new GenericUrl(reqUrl);
HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
HttpResponse response = request.execute();


InputStream is = response.getContent();
int ch;
while ((ch = is.read()) != -1) {
System.out.print((char) ch);
}
response.disconnect();
}

public boolean isOwner(String Owner) {
try {
getRequest("http://localhost:9024/login/isAuth?Username=" + Owner);
} catch (HttpResponseException e) {
System.out.println("Error: " + e.getContent());
return false;
} catch (IOException e) {
System.out.println("Could Not Connect To Site/Make Said Request. \nAre You In Testing? \nIf So This Is Ok.");
}
return true;
}
}

这是我的 Junit:

//imports

@RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {

@Mock
private EventModelRepo eventModelRepo;

@InjectMocks
private EventServiceImpl eventServiceImpl ;

@Test
public void validatePostDataTest() {
// mocking the HTTP Call in isOwner()
HttpTransport transport = new MockHttpTransport();
HttpRequest request = null;
try {
request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
} catch (IOException e) {
e.printStackTrace();
}
try {
HttpResponse response = request.execute();
} catch (IOException e) {
e.printStackTrace();
}
EventDetails eventDetails = new EventDetails("username1", "resturant", "idk", "location.", ".com",
"no", "no p", "spring", "fair", "tes");

//If Owner Isn't Validate As Owner/Signed In
when(eventServiceImpl.isOwner(anyString())).thenReturn(false);
//doReturn(false).when(eventServiceImpl).isOwner(anyString());

eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");
result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);

}
}

最佳答案

结果证明我帖子上的一位评论者是正确的。您无法模拟来自 @InjectMocks 的调用。但如果您愿意,您需要添加另一个注释。该注释是@Spy。应将此注释添加到测试类中,位于 @InjectMocks 上方。

More can be found here



@RunWith(MockitoJUnitRunner.class)
public class EventServiceTestUnit {

@Mock
private EventModelRepo eventModelRepo;

@Spy
@InjectMocks
private EventServiceImpl eventServiceImpl ;

@Test
public void validatePostDataTest() {

when(eventServiceImpl.isOwner(anyString())).thenReturn(false);

eventDetails = new EventDetails("username", "resturant", "idk", "location.", ".com",
"no", "no p", "fall", "fair", "tes");

result = eventServiceImpl.validatePostData(eventDetails);
assertEquals(10, result);

}
}

关于java - 无法为 Junit 的方法创建模拟调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58777111/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com