org.thymeleaf.TemplateEngine mockito问题

huangapple go评论95阅读模式
英文:

org.thymeleaf.TemplateEngine mockito problem

问题

@Service
public class MailTemplateCreator {

    private final TemplateEngine templateEngine;

    public MailTemplateCreator(@Qualifier("templateEngine") TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    public String buildEmailTemplate(TemplateValues values){
        Context context = new ContextBuilder()
                .addVariable("topic", EmileMassages.topic(values.getChangedData()))
                .addVariable("welcome", EmileMassages.welcome(values.getName()))
                .addVariable("message", EmileMassages.message(values.getChangedData(), values.getDataValue()))
                .addVariable("button", EmileMassages.buttonName(values.getChangedData()))
                .addVariable("change_url", EmileMassages.changeLink(values.getChangeDataLink()))
                .addVariable("goodbye", EmileMassages.goodbye())
                .addVariable("app_name", EmileMassages.appName()).build();

        return templateEngine.process("email/Email-alert-template.html", context);
    }
}
@ExtendWith(MockitoExtension.class)
class MailTemplateCreatorTest {
    @InjectMocks
    MailTemplateCreator creator;
    @Mock
    TemplateEngine templateEngine;

    @Test
    void name() {
        TemplateValues values = TemplateValues.builder()
                .changeDataLink("test link")
                .changedData("test Data")
                .dataValue("test value")
                .name("test name").build();

        when(templateEngine.process(eq("email/Email-alert-template.html"), any(Context.class))).thenReturn("Test");

        String emailHtml = creator.buildEmailTemplate(values);

        assertThat(emailHtml).isNotEmpty();
    }
}
英文:

Hi I have a problem with mock method templateEngine.process(...).

public class MailTemplateCreator {

    private final TemplateEngine templateEngine;

    public MailTemplateCreator(@Qualifier("templateEngine") TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    /** Method for inject variables for thymeleaf html template.
     * @param values class for inject values for thymeleaf context.
     * @return values inject into Email-alert-template.html.
     */
    public String buildEmailTemplate(TemplateValues values){
        Context context = new ContextBuilder()
                .addVariable("topic",EmileMassages.topic(values.getChangedData()))
                .addVariable("welcome",EmileMassages.welcome(values.getName()))
                .addVariable("message",EmileMassages.message(values.getChangedData(),values.getDataValue()))
                .addVariable("button",EmileMassages.buttonName(values.getChangedData()))
                .addVariable("change_url",EmileMassages.changeLink(values.getChangeDataLink()))
                .addVariable("goodbye", EmileMassages.goodbye())
                .addVariable("app_name",EmileMassages.appName()).build();

        return templateEngine.process("email/Email-alert-template.html",context);
    }
}
class MailTemplateCreatorTest {
    @InjectMocks
    MailTemplateCreator creator;
    @Mock
    TemplateEngine templateEngine;

    @Test
    void name() {
        //Given
        TemplateValues values = TemplateValues.builder()
                .changeDataLink("test link")
                .changedData("test Data")
                .dataValue("test value")
                .name("test name").build();

        when(templateEngine.process("email/Email-alert-template.html",any(Context.class))).thenReturn("Test");

        //When
        String emailHtml =creator.buildEmailTemplate(values);

        //Then
        assertThat(emailHtml).isNotEmpty();
    }

18:37:50.435 [main] DEBUG org.thymeleaf.TemplateEngine - [THYMELEAF] INITIALIZING TEMPLATE ENGINE

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at com.juniorstart.juniorstart.email.MailTemplateCreatorTest.name(MailTemplateCreatorTest.java:39)

This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));

For more info see javadoc for Matchers class.

at org.thymeleaf.TemplateEngine.initialize(TemplateEngine.java:328)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1079)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1059)
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1048)
at com.juniorstart.juniorstart.email.MailTemplateCreatorTest.name(MailTemplateCreatorTest.java:39)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:132)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)




</details>


# 答案1
**得分**: 1

实际上,这个问题在很长时间前就已经在 GitHub 上有[报告][1]了。问题是 Mockito 无法模拟 final 方法(这是有道理的)。解决方法是使用 `ITemplateEngine` 接口,该接口自 Thymeleaf 3.0 开始提供,如果我理解得正确的话。

将你的类的实现从 `public MailTemplateCreator(@Qualifier("templateEngine") TemplateEngine templateEngine)` 更改为 `public MailTemplateCreator(@Qualifier("templateEngine") ITemplateEngine templateEngine)`,并模拟该接口 `@Mock ITemplateEngine templateEngine;`。

现在你可以对任何你想要的内容进行存根操作,例如 `when(templateEngine.process(anyString(),any(Context.class))).thenReturn("Test");`。


  [1]: https://github.com/thymeleaf/thymeleaf/issues/314

<details>
<summary>英文:</summary>

Actually, this one has been [reported on GitHub][1] a long time ago. The problem is mockito not mocking final methods (which makes sense). The solution to this is to use the `ITemplateEngine` interface, provided since Thymeleaf 3.0 if I understood that correctly.

Change the implementation of your class from `public MailTemplateCreator(@Qualifier(&quot;templateEngine&quot;) TemplateEngine templateEngine)` to `public MailTemplateCreator(@Qualifier(&quot;templateEngine&quot;) ITemplateEngine templateEngine)` and mock that interface `@Mock ITemplateEngine templateEngine;`.

Now you can stub whatever you want, e.g. also `when(templateEngine.process(anyString(),any(Context.class))).thenReturn(&quot;Test&quot;);`.


  [1]: https://github.com/thymeleaf/thymeleaf/issues/314

</details>



huangapple
  • 本文由 发表于 2020年9月14日 00:42:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63873202.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定