提问者:小点点

@injectmocks是如何工作的


从@mock和@injectmocks之间的差异,我理解@injectmocks被用作创建实例的注释,并将用@mock创建的mock注入其中。我想我不明白它是怎么工作的。

public interface SimpleAgenda {

    public List<String> getAppointments();

    public String getAppointment(Date d);

    public void addAppointments(Date d, String label);

}
public class MyAgenda implements SimpleAgenda {

    private Map<String, String> appointments;

    @Override
    public List<String> getAppointments() {
        List<String> lst = new ArrayList<String>();
        System.out.println(this.appointments == null);
        for (String key : this.appointments.keySet()) {
            String label = this.appointments.get(key);
            lst.add(label);
        }

        return lst;
    }

    @Override
    public String getAppointment(Date d) {
        String dateString = d.toString();
        String app = this.appointments.get(dateString);
        
        return app;
    }

    @Override
    public void addAppointments(Date d, String label) {
        // TODO Auto-generated method stub
        // this behavior is not implemented yet in this class
    }

}
// @RunWith attaches a runner with the test class to initialize the test data
@RunWith(MockitoJUnitRunner.class)
public class AgendaTest {

    private static final String LABEL = "This is a mock appointment for: ";

    // @InjectMocks annotation is used to create and inject the mock object
    @InjectMocks
    MyAgenda agenda = new MyAgenda();

    // @Mock annotation is used to create the mock object to be injected
    @Mock
    Map<String, String> mockedAppointments;

    @Before
    public void createMocks() {
        Date d1 = (new GregorianCalendar(120, 4, 15)).getTime();
        Date d2 = (new GregorianCalendar(119, 7, 31)).getTime();

        String key;

        key = d1.toString();
        // add the mocked behavior of for a set of given dates
        when(mockedAppointments.get(key)).thenReturn(LABEL + key);

        key = d2.toString();
        // 1. add the mocked behavior of for a set of given dates.
        // 2. Strict stubbing that requires that all declared stubs are actually used
        //    the statement lenient() relax this requirement. Check the manual. 
        lenient().when(mockedAppointments.get(key)).thenReturn(LABEL + key);

        when(mockedAppointments.size()).thenReturn(2);
    }

    @Test
    public void mockTest() {
        for (String key : mockedAppointments.keySet()) {
            String v = mockedAppointments.get(key);
// Do not worry, we will never reach this line. We are querying the object on 
// method that was not mocked (i.e. keySet).            
            Assert.fail();
        }

        int size = mockedAppointments.size();

        Assert.assertEquals(2, size);
    }

    @Test
    public void simpleTest() {
        int appCounter = agenda.getAppointments().size();
// Do not expect that appCounter is 2 (or more in general different than 0) ... 
// we are actually querying an object that was not mocked!!!
// See the details of the implementation of the method: MyAgenda.getAppointments()
        Assert.assertEquals(0, appCounter);
    }

以下是我的问题:

  1. mocktest()中,当我调用mockedappointments.keyset()时,它返回一个空集...我的问题是:为什么mockedAppointments.keyset()不抛出nullpointerexception(只声明mockedappoinceptions)?也许因为这是一个嘲弄?如果原因是这样,为什么模拟不抛出“NullPointerException”?
  2. simpletest()中,我们有agenda.getpartications().size();Agenda.getDartications()包含system.out.println(this.aptications==null);和这行打印“false”是我保留@injectmocks注释,否则为“true”,但为什么?在第一种情况下(@injectmocks被保留),“议程”的“约会”属性在哪里初始化?它被初始化是因为我们将mocked约会的值注入其中吗?如果是,那么Mockito是否只根据测试类中定义的模拟类型和MyAgenda中定义的属性类型来执行此操作?

共1个答案

匿名用户

  1. qn为什么mockedAppointments.keyset()不抛出nullPointerException(只声明mockedappoinctions)?也许因为这是一个嘲弄?如果原因是这样的话,为什么模拟不抛出“NullPointerException”呢?
    答案是:因为mockedappointments.keyset().size是0并且mockedappointments.keyset()是空的,所以这是模拟的行为
  2. 2.0Qn system.out.println(this.appings==null);行打印“false”是我保留@injectmocks注释,否则“true”,但为什么呢?
    答案是:在junit或mockito System.out.println中不起作用,而是使用logger。
    2.1Qn在第一种情况下(@injectmocks被保留)“议程”的“约会”属性在哪里初始化?
    答案是:它是在嘲笑类,例如列表,它初始化为0,并将值保持为空,除此之外
@InjectMocks
private MyAgenda agenda;

应该像这样声明
2.2Qn它初始化是因为我们向它注入了mockeddartications的值吗?
答案是:mockeddappences和议程没有任何联系,除此之外,这个injectMocks您可以使用@mocks,它是有效的。

 @Mocks
 private MyAgenda agenda;