简体   繁体   English

我该如何为void方法创建仅更改数据并保存它的单元测试

[英]How can I create unit test for void method which just change data and save it

I have some handler(in this example I just use controller): 我有一些处理程序(在此示例中,我只使用控制器):

@RestController
public class MessageController {

    private final TaskExecutor taskExecutor;
    private final Operation operation;
    private final MessageLogService messageLogService;

    public MessageController(TaskExecutor taskExecutor, Operation operation, MessageLogService messageLogService) {
        this.taskExecutor = taskExecutor;
        this.operation = operation;
        this.messageLogService = messageLogService;
    }

    @PostMapping(value = "/process")
    public String handleMessage(MessageRequest messageRequest){

        MessageLog messageLog = messageLogService.createNewMessageLog();

        taskExecutor.execute(() -> {
            try {
                operation.process(messageLog.getGuid(), messageRequest);
            } catch (MessageLogDoesNotExistException e) {
                throw new RuntimeException(e);
            }
        });
        return "REQUEST_QUOTED";
    }
}
  1. I receive some request. 我收到一些要求。
  2. I create new MessageLog in DB with status "NEW" and some default(and some data from the request in the real project) values and save. 我在状态为“ NEW”的数据库中创建了新的MessageLog并保存了一些默认值(以及真实项目中来自请求的数据)。
  3. I send messageRequest and MessageLog's guid to the operation in the executor and return sync response "REQUEST_QUOTED" immediately. 我将messageRequestMessageLog's guid发送到operation中的operation ,并立即返回同步响应“ REQUEST_QUOTED”。

@Service
public class MessageOperation implements Operation {

        private final MessageLogService messageLogService;

        public MessageOperation(MessageLogService messageLogService) {
            this.messageLogService = messageLogService;
        }

        @Transactional
        @Override
        public void process(String guid, MessageRequest messageRequest) throws MessageLogDoesNotExistException {

            MessageLog messageLog = messageLogService.getOne(guid);

            if (messageLog == null)
                throw new MessageLogDoesNotExistException();

            try {
                Message message = createMessage(messageRequest);
                messageLog.setStatus("SUCCESS");
                messageLog.setMessage(message);
            } catch (MessageCreationException e) {
                messageLog.setStatus("FAIL");
                messageLog.setErrorCode(e.getCode());
            }
            messageLogService.save(messageLog);
        }

        private Message createMessage(MessageRequest messageRequest) throws MessageCreationException {
            //logic
            return null;
        }
    }

Into operation I create the message and bind it with messageLog. operation我创建了消息并将其与messageLog绑定。 If I create and bind success - I set status 'SUCCESS' or 'FAIL' if not. 如果我创建并绑定成功-我将状态设置为“成功”或“失败”。 And just save messageLog. 并只保存messageLog。

How can I create Unit test for operation's method process ? 如何为operation's方法process创建Unit test It is void. 它是空的。

1) I get a request from the client 1)我收到客户的请求

2) delegate the request to the new thread for the async process 2)将请求委托给新线程进行异步处理

3) return sync response. 3)返回同步响应。

And I don't understand how can I create a unit test for public void process(String guid, MessageRequest messageRequest) 而且我不明白如何为public void process(String guid, MessageRequest messageRequest)创建单元测试public void process(String guid, MessageRequest messageRequest)

In this case for MessageOperation I recommend using Mockito https://www.baeldung.com/mockito-annotations library for mocking the class attribute 在这种情况下,对于MessageOperation我建议使用Mockito https://www.baeldung.com/mockito-annotations库来Mockito class属性

@Mock
private final MessageLogService messageLogService;

Then in your unit test you use the verify() method to check that expected behaviour has happened. 然后在单元测试中,使用verify()方法检查是否发生了预期的行为。 (save is called correctly for example). (例如,正确调用了save)。

I would also mock the response of getOne to fit your need 我还将模拟getOne的响应以适合您的需求

MessageLog messageLog = messageLogService.getOne(guid);

for example 例如

MessageLog messageLog = new MessageLog();
when(messageLogService.getOne(eq("THE GUID YOU GIVE IN THE METHDO CALL"))).thenReturn(messageLog);

That way since you have the object reference to MessageLog you can check for the status in the test code: 这样,由于您具有对MessageLog的对象引用,因此可以检查测试代码中的状态:

assertEquals("SUCCESS", messageLog.getStatus());

And use verify to check that the save method is called correctly: 并使用验证检查save方法是否正确调用:

verify(messageLogService).save(same(messageLog));

About the matchers I used https://www.baeldung.com/mockito-argument-matchers 关于我使用过的匹配器https://www.baeldung.com/mockito-argument-matchers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM