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

Java 如何测试只传递其子对象并期望父对象继承其子对象的更新值的方法?,java,junit,mockito,Java,Junit,Mockito,您好,我正在尝试为一个方法创建一个测试,该方法如下(updateObject): MyService.class: public Parent updateObject(Parent parent) { otherService.updateChild(parent.getChild()); return parent; } public Child updateChild(Child child) { child.setName("updated name");

您好,我正在尝试为一个方法创建一个测试,该方法如下(updateObject):

MyService.class:

public Parent updateObject(Parent parent) {
    otherService.updateChild(parent.getChild());
    return parent;
}
public Child updateChild(Child child) {
    child.setName("updated name");
    return child;
}
OtherService.class:

public Parent updateObject(Parent parent) {
    otherService.updateChild(parent.getChild());
    return parent;
}
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());
}
任何帮助都将不胜感激

  • 首先,创建父对象和子对象,然后设置 将子对象转换为父对象
  • 在调用updateObject方法之前,断言子对象 对象的名称为空
  • 调用updateObject方法,然后断言名称设置为 “更新名称”
下面是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());
}
  • 首先,创建父对象和子对象,然后设置 将子对象转换为父对象
  • 在调用updateObject方法之前,断言子对象 对象的名称为空
  • 调用updateObject方法,然后断言名称设置为 “更新名称”
下面是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());
}

你尝试了什么?嗯,我尝试模拟updateChild方法并返回一个具有更新值的对象。。但是父对象没有得到更新。您能告诉我们您的尝试并解释到底出了什么问题吗?我已经添加了一个示例测试代码。您认为
when(otherService.updateChild(any(Child.class))。然后返回(updatedChild)
do?为什么你认为
currentChild
必须更改它的状态?你尝试了什么?嗯,我试图模拟updateChild方法并返回一个具有更新值的对象..但是父对象没有得到更新。你能告诉我们你的尝试并解释到底出了什么问题吗?我已经添加了一个示例测试代码到我所做的事情中。你做了什么你认为
when(otherService.updateChild(any(Child.class)).thenReturn(updatedChild);
do?以及为什么你认为
currentChild
必须更改它的状态?仅使用
newmyservice()
并不能清楚地说明对
otherService
的依赖关系在测试实例中是如何初始化的。只使用
newmyservice()
没有明确说明对
otherService
的依赖关系是如何在被测实例中初始化的。