gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:37:30 26 4
gpt4 key购买 nike

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

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 本身,但必须从 modifyObject() 构建并返回一个新的 SomeType 对象,该对象是 main 方法然后可以传递给下一个类进行处理

然而,这似乎在单元测试期间引发了问题。我们似乎无法从单元测试类访问内部 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

最佳答案

以下是如何使用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();

关于java - 类必须在内部创建新对象,无法从单元测试中访问该对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53172440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com