Java 伪客户机单元测试

Java 伪客户机单元测试,java,unit-testing,spring-boot,Java,Unit Testing,Spring Boot,我想知道在这种情况下编写单元测试的最佳方法是什么: MyApi: @RestController public class MyApi{ @Autowired MyAction myAction; @PostMapping public ResponseEntity addAction(@ResponseBody MyDto myDto){ return myAction.addAction(myDto); } } 我的行动: @Se

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

MyApi:

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

}
@服务
公共集体诉讼{
@自动连线
私人MyClient MyClient;
公共响应登录(MyDto MyDto){
返回ResponseEntity.ok(myClient.addClient(myDto));
} 
}
例如,是否必须添加构造函数


谢谢

我确信有一种方法可以避免使用自动生成构造函数,只需自动生成字段,但是我使用构造函数,因为我认为这是一个很好的实践。它也可以像这样注入一个被嘲弄的对象,比如“

”。
@Mock
MyAction myAction;

MyApi myApi;
ResponseEntity<AuthenticationResponseDto> testResponse = ResponseEntity.ok
                                                           (new AuthenticationResponseDto());


@Before
public void setup(){
   myApi = new MyApi(myAction);
}

@Test
public void simpleMyApiTestExample (){
  when(myAction.login(any())).thenAnswer(i-> testRespone);
  ResponseEntity<?> actualResponse = myApi.addAction(new MyDto());
  assertThat(actualResponse).isSameAs(testResponse);
}
@Mock
我的行动我的行动;
MyApi MyApi;
ResponseEntity testResponse=ResponseEntity.ok
(新的AuthenticationResponseDto());
@以前
公共作废设置(){
myApi=新的myApi(myAction);
}
@试验
public void simplemyapitest示例(){
当(myAction.login(any())。然后回答(i->testRespone);
ResponseEntity actualResponse=myApi.addAction(新的MyDto());
资产(实际响应).isSameAs(测试响应);
}

我只是想给你一个想法。我刚刚在SO文本编辑器中写了这个例子,SO对任何键入/错误都表示赞同。但希望这能说明为什么拥有构造函数对测试自动连接的东西很有用。它允许你通过将对象添加到构造函数来模拟实例化所需的对象。在这个例子中,这可能是因此,也适用于MyDto和AuthenticationResponseDto对象。

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

@RunWith(MockitoJUnitRunner.class)
public class Test {

    @Mock
    private Client client;

    @InjectMocks
    private ServiceImpl plannerService = new ServiceImpl();

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

您所说的
是什么意思?必须添加构造函数吗?