java - 测试一起运行时失败,单独运行时通过
问题描述
我有一个测试类,当我一次运行所有测试时,所有测试都通过了,除了 getLogo()。测试 getLogo() 只有在我单独运行它时才会通过,我一点也不知道为什么。
这是我的测试课:
@WebAppConfiguration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.example")
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ReceiptApplication.class})
public class PropertiesServiceTest {
@Autowired
private ConfigPropertiesService configPropertiesService;
@Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
@Test
public void uploadLogo() throws Exception {
MockMultipartFile file = new MockMultipartFile("logo", "originalMock.jpg", null, "bar".getBytes());
mockMvc
.perform(multipart("/settings/uploadLogo").file(file))
.andExpect(status().isOk());
}
@Test
public void getLogo() throws Exception {
mockMvc
.perform(get("/settings/getLogo"))
.andExpect(status().is(200));
}
@Test
public void deleteLogo() throws Exception {
mockMvc
.perform(delete("/settings/deleteLogo"))
.andExpect(status().is(200));
}
}
我得到的例外是
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
端点 /getLogo 如下所示:
@GetMapping(value = "/getLogo")
public String getLogo() {
return new Gson().toJson(configPropertiesService.getLogo());
}
configPropertiesService 中的 getLogo 方法:
public byte[] getLogo() {
ConfigPropertiesEntity configPropertiesEntity = configPropertiesRepository.findByName("com.example.logoName");
if (configPropertiesEntity != null) {
try {
InputStream in = getClass().getResourceAsStream("/static/photos/" + configPropertiesEntity.getValue());
return IOUtils.toByteArray(in);
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
我知道为什么我得到一个 NullPointerException,这是因为当测试与其他文件一起运行时找不到该文件,在这种情况下应用程序运行到 catch 块中。但是为什么当我单独运行测试时不会发生这种情况?我如何更改测试,以便在我一起运行它们时它们也通过?
解决方案
推荐阅读
- discord.py - 如果另一个用户发送消息,你如何制作一个发送消息的不和谐机器人?不和谐.py
- reactjs - React.js 没有从我的 .sass 文件中应用样式
- css - 为什么路径的第 n 个孩子不可访问?
- python - AttributeError:'pygame.Surface'对象没有属性'get'(python 2.7.5)
- matlab - 在 Matlab 中使用 Sobel 掩码进行边缘检测此代码不接受下面提到的行
- telerik - 将 Telerik Blazor Control 连接到实体和 Ardalis.SmartEnum
- google-analytics - gatsby-plugin-google-analytics + Shopify - 转换不起作用
- bash - 安排工作每隔一天运行一次的最佳方法?
- python - Matlab在Python中重塑等价物
- sql-server - 在 Docker 容器中的 Server Core 2019 上安装 SQL Server LocalDB