Mockito 出现问题并在我测试我的服务时说未定义类型

Mockito problems and says undefinied type while ı am testing my service

我正在编写单元测试,但我遇到了一些错误。我正在尝试测试我的 ServiceImpl,只是在下面我的代码下方显示我的整个代码;

我的服务Class

@Service
public class PlaneServiceImpl implements PlaneCallerService {

    private final PlaneFactory planeFactory;

    public PlaneServiceImpl(PlaneFactory planeFactory) {
        this.planeFactory = planeFactory;
    }

    @Override
    public String getPlaneType(String planeType) {

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append(planeFactory.getPlane(planeType).getType());
        stringBuilder.append(" Plane has produced.");

        return stringBuilder.toString();
    }

平面class往下

public interface Plane {

    String getType();
}

下面是我的 PlaneFactory class;

@Component
public class PlaneFactory {

public Plane getPlane(String planeType) {

    if (StringUtils.isBlank(planeType)) {
        throw new PlaneTypeNotFoundException();
    }

    if (planeType.equalsIgnoreCase("lightJet")) {
        return new LightJet();

    } else if (planeType.equalsIgnoreCase("midJet")) {
        return new MidJet();

下面是我的模拟测试

public class PlaneCallerServiceImplTest {

    private PlaneFactory planeFactory;
    private PlaneCallerService planeCallerService;
    private plane plane;

    @Before
    public void setUp() {

        planeFactory = mock(PlaneFactory.class);
        planeCallerService = new PlaneCallerServiceImpl(planeFactory);
        plane= mock(Plane.class);

    }

    @Test
    public void testPlaneType() {

        String planeType = "";

        when(planeFactory.getPlane(planeType)).thenReturn(plane);

        String result = planeCallerService.getplaneType(planeType);

        assertNotNull(result);

    }
}

我得到 The method getPlane(String) is undefined for the type PlaneFactory

我对单元测试和模拟测试都很陌生,如有任何帮助,我们将不胜感激 提前谢谢你

您的问题来自以下陈述:

when(planeFactory.getPlane(planeType)).thenReturn(plane);

您正在返回类型为 Plane 的模拟响应,但在您调用 Plane.getType() 时该模拟响应中未实现该方法。

你也可以模拟它的响应,添加

when(plane.getType()).thenReturn("SOME_MOCKED_STRING");

这应该开始工作了。

下面是完整的测试class:

public class PlaneServiceImplTest {

    private PlaneFactory planeFactory;
    private PlaneServiceImpl planeCallerService;

    @Before
    public void setUp() {

        planeFactory = mock(PlaneFactory.class);
        planeCallerService = new PlaneServiceImpl(planeFactory);
    }

    @Test
    public void testPlaneType() {
        Plane plane = mock(Plane.class);
        when(planeFactory.getPlane(anyString())).thenReturn(plane);
        
        String result = planeCallerService.getPlaneType("Test");

        assertNotNull(result);
    }
}