无法为Junit方法创建模拟调用

嗨,我是Junit和Mockito的新手,所以请简单介绍一下Ive的一些误解/错误。我有一个我想测试的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","fall","tes");
        result = eventServiceImpl.validatePostData(eventDetails);
        assertEquals(10,result);

    }
}
shangcangcun 回答:无法为Junit方法创建模拟调用

因此,我发布的评论者之一是正确的。您无法模拟来自@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);

    }
}
本文链接:https://www.f2er.com/3133753.html

大家都在问