-1
package com.leopard.spring;

import java.time.LocalTime;
import org.springframework.stereotype.Service;

@Service
public class MessageBean {

public String getMessage() {
    return "Button was clicked at " + LocalTime.now();
     }
}
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
Mcstang94
  • 31
  • 1
  • 5
  • What are you trying to test? While it may be possible to mock `LocalTime.now()` you need a specialized mocking framework (e.g. powermock). Be aware that PowerMock does some bytecode manipulation, though. – Turing85 Jul 27 '19 at 15:35
  • 1
    Code like this is so simple I wouldn't bother to test it. – markspace Jul 27 '19 at 15:36
  • 1
    @markspace Sorry, but this is not true. When you follow tdd, you test everything that your code is doing. Bugs can hide in simple code, too. And when someone comes here and asks "I want to learn unit testing, so how to do it" then "testing not required for simple code" is a very bad suggestion. – GhostCat Jul 27 '19 at 16:27
  • @Turing85 not true. LocalDate was designed to be testable! See https://stackoverflow.com/a/32794740/1531124... So powermock is the completely wrong guidance here. And a newbie will not understand what the implications of powermock are. "experts tell me I need it" so why not use it?! So, no: everybody here forget about powermock please! – GhostCat Jul 27 '19 at 16:28

1 Answers1

0

There's not much to test on this class. The only thing you can test is that it returns a string, and that it matches the message format. Obvioulsly you can't test the exact time you'll get, but you can expect it to start with the message:

@Test
public void testGetMessage() {
  String expectedMessagePrefix = "Button was clicked at ";
  String message = testedClass.getMessage();
  assertTrue("did not get the expected message", message.startsWith(expectedMessagePrefix));
}
Nir Levy
  • 12,750
  • 3
  • 21
  • 38
  • "*Obvioulsly you can't test the exact time you'll get...*" - Oh you can, through e.g. powermock, but I wouldn't recommend it. Additionally, you could validate the date format through regex (if this is desired). – Turing85 Jul 27 '19 at 15:40
  • @Turing85 seems like an over-kill for such method, but yes, powermock is always an option – Nir Levy Jul 27 '19 at 15:47
  • 1
    Powermock isn't an option, it is your last resort, only to be used when testing old code that can't be tested otherwise. In any other case, you write easy to test code... And when you think "I need powermock" then you already know: "my production code isn't easy to test, thus it should be improved". For now() you can easily test via using a custom clock, see https://stackoverflow.com/a/32794740/1531124 – GhostCat Jul 27 '19 at 16:25