代码之家  ›  专栏  ›  技术社区  ›  James Relic

使用Mockito对基于Guice的类进行单元测试

  •  0
  • James Relic  · 技术社区  · 8 年前

    我的应用程序使用Google Guice依赖注入框架。我现在很难找到为我的类编写单元测试的方法。

    private final Person aRecord;
    
    @Inject
    public MyClass(Venue venue, @Assisted("record") Record myRecord) {
        super(venue,myRecord);
        aRecord = (Person) myRecord;
    }
    
    public void build() throws Exception {
        super.build();
        super.getParentRecord().setJobType(aRecord.getJobType());
        super.getParentRecord().setHairColor(aRecord.getHairColor());
        super.getParentRecord().setEyeColor(aRecord.getEyeColor());
    }
    

    我想在子类中为build()方法编写一个单元测试,它应该

    • 确保当超级。build()将调用super上的所有基本信息。getParentRecord()已填充,例如年龄、性别等。
    • 如果记录,请确保在build()方法中引发异常。getJobType()为null
    • 如果记录,请确保在build()方法中引发异常。getHairColor()为空
    • 如果记录,请确保在build()方法中引发异常。getEyeColor()为空
    1 回复  |  直到 8 年前
        1
  •  1
  •   Evgeni Dimitrov    8 年前

    MyClass有两个依赖项(场地和录制),所以你必须模仿它们。

    import static org.mockito.Mockito.mock;
    import static org.mockito.Mockito.when;
    ...
    Venue venueMock = mock(Venue.class);
    Record recordMock = mock(Record.class);
    

    然后在单元测试中,您必须创建 MyClass 并断言预期结果:

    例如:“如果aRecord.getJobType()为null,请确保在build()方法中引发异常”

    @Test(expected=RuntimeException.class)// or whatever exception you expect
    public void testIfExceptionIsThrownWhengetJobTypeReturnsNull() throws Throwable {
        Venue venueMock = mock(Venue.class);   //create the mocks
        Record recordMock = mock(Record.class);//create the mocks
        when(recordMock.getJobType()).thenReturn(null); //specify the behavior of the components that are not relevant to the tests
    
        MyClass myClass = new MyClass(venueMock, recordMock); 
        myClass.build();
        //you can make some assertions here if you expect some result instead of exception
    }
    

    注意,如果没有指定任何模拟依赖项的返回值(使用 when() )它将返回返回类型的默认值-对象为null,基元数为0,布尔值为false,等等。因此,最好存根中使用的所有方法 类名 .