类必须在内部创建新对象,无法从单元测试中访问

时间:2018-11-06 13:01:22

标签: java unit-testing junit junit4 junit5

我们有一个类,其目的是更改已接收对象的某些字段中的值,并保留其其他字段中的值

public void process(SomeType someObject) {
  SomeType modifiedObject = modifyObject(someObject);
  nextClass.process(modifiedObject);
}

private SomeType modifyObject(SomeType someObject) {
  String someValueFromServiceCall = someService.getSomeValue(...);
  SomeType modifiedObject = new SomeType.Builder()
                                        .withSomeFieldValuesFromSomeObjectItself(...)
                                        .withSomeFieldValuesFromServiceCall(someValueFromServiceCall)
                                        .build();
  return modifiedObject;
}

SomeType是一个遗留类,我们只能使用其构建器类来创建它,而没有setter方法。这意味着我们不能修改接收到的someObject本身,而必须从SomeType构建并返回一个新的modifyObject()对象,然后该main方法可以将其传递给下一个类进行处理< / p>

但是,这似乎在单元测试中引起了问题。我们似乎无法从单元测试类访问内部modifiedObject,例如我们似乎无法对此做出期望/声明

SomeType someObject = createSomeObjectForTest();
expect(someServiceMock.getSomeValue(...)).andReturn(SOME_VALUE);
expect(nextClassMock.process(someObject)).andReturn(...); //this is not someObject, but the new internal modifiedObject created within underTest
underTest.process(someObject);
assertEquals(someObject.getSomeField(), SOME_VALUE); //this is not someObject, but the new internal modifiedObject created within underTest

1 个答案:

答案 0 :(得分:1)

以下是使用ArgumentCaptor的方法:

// mock and make sure all fields required for modify are set
SomeType arg = create(); 
ArgumentCaptor<SomeType> captor = ArgumentCaptor. forClass(SomeType.class);

sut.process(arg) ;

verify (nextClass). process(captor.capture());
SomeType modified = captor.get();