当前位置: 首页 > 知识库问答 >
问题:

当方法调用未被调用时,验证返回消息“想要但未被调用,实际上,与此mock没有任何交互”

姬存
2023-03-14

下面是我要测试的代码类

public class ClassA{
    private ClassB bb = new ClassB();

    public boolean init() {

        bb= new ClassB();
        bb.init();

        return true;
}

    public void methodToTest(){    
        Map<String, Map<String, Integer>> hashmap= new LinkedHashMap<>();

        hashmap = bb.method1(hashmap);
    }

    public ClassB getBB() {
       return bb;
    }

    public void setBB(ClassB bb) {
       this.bb= bb;
    }
}

我的测试类

@RunWith(PowerMockRunner.class)
public class TestClassA {       

    @Test
    @PrepareForTest({Utilities.class, Logger.class, LoggerFactory.class})
    public void getData() throws JsonProcessingException, JSONException {


        Map<String, Map<String, Integer>> hashmap= new LinkedHashMap<>();
        Map<String, Map<String, Integer>> newHashmap= new LinkedHashMap<>();

        ClassA class2Test= new ClassA ();
        ClassB mockClassB= Mockito.mock(ClassB.class);



PowerMockito.whenNew(ClassB.class).withAnyArguments().thenReturn(mockClassB);
        Mockito.when(mockClassB.method1(hashmap)).thenReturn(newHashmap);
        Mockito.verify(mockClassB).method1(hashmap);

        class2Test.methodToTest();



    }
}

共有1个答案

胡承悦
2023-03-14

我想你把一些东西混在一起了。

对于重构的版本,您需要将classb的模拟注入到classa中(不需要使用powermockito.whennew)。

还要注意,verifiy调用必须在测试方法调用之后。

@RunWith(PowerMockRunner.class)
public class SampleTest {

    static class ClassB {
        public Map<String, Map<String, Integer>> method1(Map<String, Map<String, Integer>> hashmap) {
            return null;
        }
    }

    static class ClassA {

        private ClassB bb = new ClassB();

        public void methodToTest() {

            Map<String, Map<String, Integer>> hashmap = new LinkedHashMap<>();
            hashmap = bb.method1(hashmap);
        }
    }

    @Mock
    ClassB bb;

    @InjectMocks
    ClassA class2Test;

    @Test
    public void test() throws Exception {

        Map<String, Map<String, Integer>> hashmap = new LinkedHashMap<>();
        Map<String, Map<String, Integer>> newHashmap = new LinkedHashMap<>();

        Mockito.when(bb.method1(hashmap)).thenReturn(newHashmap);
        class2Test.methodToTest();

        Mockito.verify(bb).method1(hashmap);
    }
}
@Test
@PrepareForTest(ClassA.class)
public void test() throws Exception {

    Map<String, Map<String, Integer>> hashmap = new LinkedHashMap<>();
    Map<String, Map<String, Integer>> newHashmap = new LinkedHashMap<>();

    ClassB bb = Mockito.mock(ClassB.class);
    Mockito.when(bb.method1(hashmap)).thenReturn(newHashmap);

    PowerMockito.whenNew(ClassB.class).withAnyArguments().thenReturn(bb);

    ClassA class2Test = new ClassA();
    class2Test.methodToTest();

    Mockito.verify(bb).method1(hashmap);
}
 类似资料: