我正在尝试测试实现类,在该类中,我为接口创建基于构造函数的自动装配。
我不打算更改此类或自动装配的方式。
在为实现类编写测试用例时,我遇到了NullPointerException,因为在Implementation类中创建了对象
具有不同的对象引用,并且模拟对象具有不同的引用值。
谁能告诉我如何模拟对象。
实现类
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() ) );
}
更新:调试Test类时,对象repositoryInterface
when( repositoryInterface.findById( "Id-123456789" )).thenReturn( c1 );
创建参考值(23425634534 @ 2005),以及
ImplementationClass称为repositoryInterface
DomainClass getDetDocument =repositoryInterface.findById( Id ).orElse( null );
ImplementationClass中的int具有参考值(23425634534 @ 1879)。因此,我正在获取getDetDocument的
null
。 最佳答案
经过所有研究,通过更改构造函数创建对象的方式使其工作。
// @Mock //removed this annotation
RepositoryInterface repositoryInterface;
@Before
public void setUp() {
repositoryInterface = mock(RepositoryInterface.class)
ImplementationClass = new ImplementationClass(repositoryInterface);
MockitoAnnotations.initMocks( this );
}
参考:https://mhaligowski.github.io/blog/2014/05/30/mockito-with-both-constructor-and-field-injection.html