尝试在@Before 中实例化一个对象

Trying to instantiate an Object in @Before

我想测试 HerePoiSearchTransformers.class 但出现以下错误:java.lang.NullPointerException

我有以下单元测试testTransformProviderResponse:

public class HerePoiSearchTransformerTest {
    private static final String ADDRESS_CATEGORIES = "city-town";

    @Rule
    public ErrorCollector collector = new ErrorCollector();

    private final HerePoiSearchTransformer transformer = new HerePoiSearchTransformer();

    // private final AddressDistrictCity addressDistrictCity = new AddressDistrictCity();
    private AddressDistrictCity addressDistrictCity;

    @Before
    public void setUp() {
        Whitebox.setInternalState(transformer, "hereAddressCategories", ADDRESS_CATEGORIES);
        transformer.initHereCategoryClassification();

        addressDistrictCity = new AddressDistrictCity();
    }
    
      @Test
    public void testTransformProviderResponse() throws IOException, OnlinePOIsearchException {
        final ProviderResponse hereResponse = new ProviderResponse();
        hereResponse.setContent(content);

        final List<PoiBE> pois = transformer.transformToPoiBEs(hereResponse);
        final PoiBE poi = pois.get(0);
        assertThat(poi.getDetails()).isNotNull();
    }
 }

!! 问题是 AbstractHereTransformers 中的 AddressDistrictCity 为空 !!

我有以下结构:

 class HerePoiSearchTransformers extends AbstractHereTransformer 
   Methods: 
        transformToPoiBEs(...) {
            transformItems(...);
         }
        transformItems(...) {
              addAddress(final AddressDO resultAddress, final PoiBE poi)
        }
   
   class AbstractHereTransformers {
       @Inject
       private AddressDistrictCity addressDistrictCity;

       protected void addAddress(final AddressDO resultAddress, final PoiBE poi) {
            addressDistrictCity.setDistrictAndCity(address, resultAddress.getDistrict(), resultAddress.getCity());
    }
  }

我认为 private final AddressDistrictCity addressDistrictCity = new AddressDistrictCity(); 会解决问题。

HerePoiSearchTransformer里面的AddressDistrictCity没有初始化

您创建了一个变量 addressDistrictCity = new AddressDistrictCity();,但这不是 transformer 中存在的对象。

您可以在 HerePoiSearchTransformer 上使用 @InjectMocks,在 AddressDistrictCity

上使用 @Mock
@InjectMocks private HerePoiSearchTransformer transformer;
@Mock private AddressDistrictCity addressDistrictCity;

JUnit 框架将负责用 AbstractHereTransformers class.

中所需的模拟对象替换 addressDistrictCity