在Junit测试中,如何实例化要测试的类中的对象是一个抽象类?

在Junit测试中,如何实例化要测试的类中的对象是一个抽象类?,junit,java-8,guice,autowired,Junit,Java 8,Guice,Autowired,下面我有一个类,我想为它编写一个单元测试 abstract class ProductImpl{ @Inject DataServices ds; // using Guice public Response parse(String key, Long value){ Response res = ds.getResponseObject(); // Response object is created using DataServices object

下面我有一个类,我想为它编写一个单元测试

abstract class ProductImpl{
   @Inject DataServices ds; // using Guice 

   public Response parse(String key, Long value){
      Response res = ds.getResponseObject(); // Response object is created using DataServices object
      res.id = key;
      res.code = value;

   }
}
我有一个测试如下

class ProductImplTest{

@InjectMocks ProductImpl impl;
Map<String, Long> map;

@Before
 map.put("abc", 10L);
 map.put("xyz", 11L);
}

@Test
public void test(){
  for(String key: map.keySet()){
    Response res = impl.parse(key, map.get(key));
    // and check if fields of Response object are set correctly i.e res.id is abc and value is 10L
  }
}
类测试{
@InjectMocks ProductImpl impl;
地图;
@以前
地图放置(“abc”,10L);
地图放置(“xyz”,11L);
}
@试验
公开无效测试(){
for(字符串键:map.keySet()){
Response res=impl.parse(key,map.get(key));
//并检查响应对象的字段设置是否正确,即res.id为abc,值为10L
}
}
但是,当我调试测试和控制转到parse方法时,DataServices对象ds为null。如何通过测试实例化这个对象。我不想使用mocking,我希望创建真正的响应对象并测试其中设置的值。

您可以使用Mockito

@RunWith(MockitoJUnitRunner.class)
class ProductImplTest {
    @Mock DataService dService;
    @InjectMocks ProductImpl sut;

    @Test
    public void test() {
        ResponseObject ro = new ResponseObject();

        String string = "string";
        Long longVal = Long.valueOf(123);

        sut.parse("string", longVal);

        verify(dService).getResponseObject();
        assertThat(ro.getId()).isEqualTo("string");
        // you should use setters (ie setId()), then you can mock the ResponseObject and use
        // verify(ro).setId("string");
    }
}
编辑:

如果
ResponseObject
是一个抽象类,或者最好是一个接口,那么

interface ResponseObject {
    void setId(String id);
    String getId();
    // same for code
}
在你的测试中

@Test public void test() {
    ResponseObject ro = mock(ResponseObject.class);
    // ... same as above, but
    verify(dService).getResponseObject();
    verify(ro).setId("string"); // no need to test getId for a mock
}

尝试构造函数注入:

class ProductImpl{
   DataServices ds;

   @Inject 
   public ProductImpl(DataServices ds) {
     this.ds = ds;
   }
}

谢谢。如果我的ProductImpl是一个抽象类,它会是什么样子呢?您不能创建抽象类的实例,所以测试它是没有意义的。当然,如果你有一个真正的类来扩展它,那么你应该测试一个真正的类。谢谢。如果我的ProductImpl是一个抽象类,它会是什么样子class@tech_ques添加了对
响应对象
接口的测试。@daniu OP指的是
ProductImpl
是抽象的哦,我明白了。这取决于它的抽象性。这可能是另一个问题。