如何测试仅传递其子对象并期望父对象继承其子对象的更新值的方法?

时间:2016-08-31 11:59:39

标签: java junit mockito

您好我正在尝试为类似这样的方法创建测试( updateObject ):

MyService.class:

public Parent updateObject(Parent parent) {
    otherService.updateChild(parent.getChild());
    return parent;
}

OtherService.class:

public Child updateChild(Child child) {
    child.setName("updated name");
    return child;
}

我试图模拟updateChild方法并返回一个带有更新值的对象..但是父对象没有得到更新的子对象。

我的失败测试:

public void testUpdateObject() {
   Parent parent = new Parent();
   Child currentChild = new Child();
   child.setName("current name");
   parent.setChild(currentChild);

   Child updatedChild = new Child();
   updatedChild.setName("updated name");

   when(otherService.updateChild(any(Child.class)).thenReturn(updatedChild);

   sut.updateObject(parent);

   assertEquals(updatedChild.getName(), parent.getChild().getName());
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

  • First, create a Parent object and a Child object and then set this child object into the parent object.
  • Before calling the updateObject method, assert that the child object's name is null.
  • Call the updateObject method and then assert that the name is set to "updated name".

So here is the test method for updateObject

@Test
public void testUpdateObject() {
  MyService myService = new MyService();

  Child child = new Child();

  Parent parent = new Parent();
  parent.setChild(child);

  asserNull(parent.getChild().getName());

  myService.updateObject(parent);

  assertEquals("updated name", parent.getChild().getName());
}