代码之家  ›  专栏  ›  技术社区  ›  Sebastien Lorber

使用Mockito进行单元测试(部分模拟)

  •  3
  • Sebastien Lorber  · 技术社区  · 15 年前

    我对莫基托有意见。

    是否可以这样做:

    ClassX x = mock(ClassX.class)
    when(x.methodB()).thenReturn("toto");
    String result = x.methodA();
    

    我在和Mockito 1.7合作。

    我看到有一个“间谍”系统,但他们说不建议使用它(为什么?)在我们测试的项目上…

    我试过那个间谍功能,但我有一种奇怪的行为。

    检查我要执行的操作:

    实数编码:

    String methodA(String arg) {
        return this.methodB(arg);
    }
    
    String methodB(String arg) {
        return "toto";
    }
    

    测试代码:

    @Test
    public void testTest() {
        final ClassX x = spy( new ClassX() );
        final String argument = "arg";
        doReturn("good").when(helper).methodB(argument);
        assertTrue(  x.methodB(argument).equals("good") );
        assertTrue(  x.methodA(argument).equals("good") );
    }  
    

    正如他们所说,我避免了when-thenreturn语法,这可能是间谍的问题(但它也不起作用)。

    奇怪的是: 断言真(x.methodb(argument.equals(“good”)); 可以

    只有第二个 断言真(x.methoda(argument.equals(“good”)); 不好

    实际上,helper.methoda(参数)返回“toto”->实际结果,而不是模拟结果

    在这种情况下,是不可能让莫基托返回“好”的????当测试类调用methodb时似乎没问题,但是如果spy的方法调用methodb,它就不再工作了…

    我不知道该怎么办…对同一类的2个方法进行单元测试,并使测试彼此独立,这样一个著名的模拟测试框架就不能实现这个基本功能,这是不是很奇怪?这不是我们所说的真正的单元测试吗?不明白为什么他们说要避免在测试对象上使用间谍方法…

    谢谢

    2 回复  |  直到 15 年前
        1
  •  2
  •   Christoffer Hammarström    15 年前

        2
  •  4
  •   Fred Haslam    15 年前

    import org.junit.Test;
    import static org.junit.Assert.*;
    import static org.easymock.EasyMock.*;
    
    public class PartialMockTest {
    
        class ClassX {
            String methodA(String arg) {return methodB(arg);}
            String methodB(String arg) {return "toto";}
        }
    
        @Test
        public void MockitoOnClassX(){
            ClassX classx = mock(ClassX.class);
            when(classx.methodB("hiyas")).thenReturn("tomtom");
            when(classx.methodA(anyString())).thenCallRealMethod();
            String response = classx.methodA("hiyas");
            assertEquals("tomtom",response);
        }
    
    
        @Test
        public void OverrideOnClassX() {
            ClassX classx = new ClassX(){@Override String methodB(String arg){return "tomtom";}};
            String response = classx.methodA("hiyas");
            assertEquals("tomtom",response);
        }
    
        @Test
        public void PartialMockOnClassX() throws NoSuchMethodException {
            ClassX classx = createMockBuilder(ClassX.class).addMockedMethod("methodB").createMock();
            expect(classx.methodA("hiyas")).andReturn("tomtom");
            replay(classx);
            String response = classx.methodA("hiyas");
            assertEquals("tomtom",response);
        }
    
    }
    
    推荐文章