1

我需要在测试类中LocalDate.now()模拟这两个静态方法。LocalTime.now()

我正在使用 PowerMock,但在尝试运行测试时收到此错误:

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

我曾尝试在测试类和配置类中创建 RestTemplate.class 的@Bean,但错误仍然存​​在。

仅当我使用PowerMockRunner.class. 如果我尝试在SpringRunner.class一切正常的情况下运行它,但我无法模拟 LocalDate 和 LocalTime。

这是我的测试课:

@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"));
    }
}
4

0 回答 0