【发布时间】:2019-04-22 13:22:42
【问题描述】:
我正在尝试测试实现类,其中我正在为接口创建基于构造函数的自动装配。 我不打算改变这个类或它的自动装配方式。
在为实现类编写测试用例时,我收到 NullPointerException,因为在实现类中创建了对象 具有不同的对象引用,模拟对象具有不同的引用值。
谁能告诉我如何模拟这个对象。
实现类
public class ImplementationClass implements ClientClass {
private final RepositoryInterface repositoryInterface;
@Autowired
public ImplementationClass( RepositoryInterface repositoryInterface ) {
this.repositoryInterface = repositoryInterface;
}
@Autowired
AAA aaa;
@Autowired
BBB bbb;
@Autowired
CCC ccc;
public DomainClass getDetails( String Id ) {
// aaa, bbb, ccc usage
DomainClass getDetDocument =
repositoryInterface.findById( Id ).orElse( null );
}
单元测试类
@Mock
RepositoryInterface repositoryInterface;
@Mock
DomainClass DomainClass;
@Mock
AAA aaa;
@Mock
BBB bbb;
@Mock
CCC ccc;
@InjectMocks
ImplementationClass implementationClass;
@Before
public void setUp() {
MockitoAnnotations.initMocks( this );
}
@Test
public void getDetTest() {
DomainClass dc = new DomainClass();
dc.setId( "Id-123456789" );
dc.setDetailsList( <Some list> );
Optional<DomainClass> c1 = Optional.of( dc );
// when().thenReturn(); // aaa, bbb, ccc usage
when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
DomainClass c2 = implementationClass.getDetails( "Id-123456789" );
assertThat( c2.getDetailsList(), equalTo( c1.getDetailsList() ) );
}
更新:在调试测试类时,对象 repositoryInterface when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
创建一个参考值 (23425634534@2005) 并且当
ImplementationClass 被称为 repositoryInterface DomainClass getDetDocument =repositoryInterface.findById( Id ).orElse( null );
在 ImplementationClass 中有一个参考值 (23425634534@1879)。因此,我为 getDetDocument 获得了null。
【问题讨论】:
-
询问异常时,总是发布异常的完整堆栈跟踪。
-
这是我在控制台中遇到的用户定义异常。但是在调试时,我得到了实现类中语句
DomainClass getDetDocument = repositoryInterface.findById( Id ).orElse( null );的null值。那是因为,repositoryInterface对象引用值在实现类和测试类中是不同的。
标签: java spring-boot junit mocking mockito