mockito问题,并表示未定义的类型ı 我在测试我的服务

mftmpeh8  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(253)

我正在写单元测试,但我面临着一个错误。我是triyng来测试我的serviceimpl只是在下面的代码下面显示我的整个代码;
我的服务级别

@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();
    }

下面是飞机舱

public interface Plane {

    String getType();
}

我的飞机工厂下课了;

@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 我是新的单元测试和模拟测试任何帮助将不胜感激,谢谢你在先进的

sshcrbum

sshcrbum1#

你的问题是,从下面的声明:

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

您正在返回类型为的模拟响应 Plane 但当你打电话的时候,那嘲笑的回应 Plane.getType() 该方法未实现。
你也可以嘲笑这种React

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

这应该开始起作用了。
下面是完整的测试类:

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);
    }
}

相关问题