gpt4 book ai didi

java - 如何在 testet 方法中编写带有断言的单元测试?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:01 26 4
gpt4 key购买 nike

我有一个问题,我喜欢在我的 junit 测试中测试一些被另一种方法隐藏的值。你怎么会这样的事情。与莫基托?子类化?

这里的问题:

public class MyService extends AbstractService {

public ResponseObject insert(SomeData data) {
Request request = createRequest(data);
Response response = new Response();
callService(request, response);
return createResponseObject(response);
}

protected void callBackendService(...) {
...
}
}

您将如何测试传递给

的值
callBackendService()
method?

Is there a more elegant way than use subclassing?

 MyService service = new MyService() {

@Override
protected void callBackendService(...) {
assertEquals(...);
...
}
}

问候,

迈克

最佳答案

一种观点认为,您应该只对公共(public)类(class)进行单元测试。因此,只需对从 insert() 返回的 ResponseObject 进行断言。

否则,使用像 Mockito 这样的模拟框架,您可以将 callBackendService() 方法分解到它自己的类中(例如 ServiceCaller)。然后您可以创建一个模拟 ServiceCaller 对象并验证传递给它的参数。

像这样的……

public class ServiceCaller  {

public callBackendService(Request request, Response response) {
...
}

}

那么你的类应该看起来像这样......

public class MyService extends AbstractService {


private ServiceCaller serviceCaller;

public ResponseObject insert(SomeData data) {
Request request = createRequest(data);
Response response = new Response();
serviceCaller.callBackendService(request, response);
return createResponseObject(response);
}

public setServiceCaller(ServiceCaller caller) {
this.serviceCaller = caller;
}

}

最后 Mockito 测试是这样的......

@Test
public void testInsert() throws Exception {

// object to test
MyService ms = new MyService();

// test input values
Request req = new Request();

Response resp = new Response();

// create a mock class and inject it into your test class
ServiceCaller sc = mock(ServiceCaller.class);

ms.setServiceCaller = sc;

// execute the method under test
ms.insert(req, resp);

// now you can see if your mock was called with the expected params
verify(sc).callBackendService(req, resp);
}

为简洁起见,我省略了使用接口(interface)等进行的良好设计,但您会明白这一点。

关于java - 如何在 testet 方法中编写带有断言的单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840025/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com