I need to mock the two static methods LocalDate.now()
and LocalTime.now()
in a testing class.
I'm using PowerMock but I receive this error when I try to run the test:
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.client.RestTemplate]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: Could not initialize class javax.xml.transform.FactoryFinder
I had try to create a @Bean of RestTemplate.class inside the test class and configuration class but the error persists.
I have this error only if I run the test with PowerMockRunner.class
. If I try to run it with SpringRunner.class
everything is fine but I can't mock the LocalDate and LocalTime.
This is my Test class:
@PrepareForTest(LocalDate.class)
@RunWith(PowerMockRunner.class)
@SpringBootTest(webEnvironment = RANDOM_PORT, classes = ChallengeApplication.class)
@ActiveProfiles("test")
public class MockTest {
@Autowired
private TestRestTemplate restTemplate;
private URL base;
@LocalServerPort
int port;
User user = new User("user", "password", "user@test.com");
HttpEntity<User> userRequest = new HttpEntity<>(user);
Mock mock = new Mock(new BigDecimal(20));
HttpEntity<Mock> request = new HttpEntity<>(mock );
@Before
public void setUp() throws MalformedURLException {
restTemplate = new TestRestTemplate();
base = new URL("http://localhost:" + port + "/mock/users");
restTemplate.postForEntity(base.toString(), userRequest, String.class);
restTemplate = new TestRestTemplate(user.getUsername(), user.getPassword());
base = new URL("http://localhost:" + port + "/mock/mocks");
}
@Test
public void wrongUserAuth_ThenFailed() throws IllegalStateException {
restTemplate = new TestRestTemplate("test", "test");
ResponseEntity<String> response = restTemplate.postForEntity(base.toString(), request, String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}
@Test
public void createTwoAccountsForTheSameUser_ThenFailed() throws IllegalStateException {
restTemplate.postForEntity(base.toString(), request, String.class);
ResponseEntity<String> responseTwo = restTemplate.postForEntity(base.toString(), request, String.class);
assertEquals(HttpStatus.CONFLICT, responseTwo.getStatusCode());
assertTrue(responseTwo
.getBody()
.contains("mock"));
}
@Test
public void createAccountDuringWeekend_ThenFailed() throws IllegalStateException {
LocalDate date = LocalDate.of(2000, 1, 1);
PowerMockito.stub(PowerMockito.method(LocalDate.class,"now")).toReturn(date);
ResponseEntity<String> response = restTemplate.postForEntity(base.toString(), request, String.class);
assertEquals(HttpStatus.CONFLICT, response.getStatusCode());
assertTrue(response
.getBody()
.contains("mock"));
}
}