首页 > 解决方案 > Feign客户端单元测试

问题描述

我想知道在这种情况下编写单元测试的最佳方法是什么:

我的API:

@RestController
public class MyApi{

    @Autowired
    MyAction myAction;

    @PostMapping
    public ResponseEntity addAction(@ResponseBody MyDto myDto){
        return myAction.addAction(myDto);
    }
}

我的行动:

@Service
public class MyAction{

    @Autowired
    private MyClient myClient;

    public ResponseEntity<AuthenticationResponseDto> login(MyDto myDto{
        return ResponseEntity.ok(myClient.addClient(myDto));
    } 

}

例如,是否必须添加构造函数?

谢谢

标签: javaunit-testingspring-boot

解决方案


使用构造函数注入被认为是一种很好的做法,但是如果您不想使用它,则需要使用@Mockand @InjectMocks。它使用反射,不需要定义构造函数。

@RunWith(MockitoJUnitRunner.class)
public class Test {

    @Mock
    private Client client;

    @InjectMocks
    private ServiceImpl plannerService = new ServiceImpl();

    @Test
    public void test() throws Exception {
        ....
    }
}

推荐阅读