java - Junit如何在测试方法中模拟方法返回?
问题描述
我通过以下方法的测试得到了 NullPointerException 但在评论后我编辑了我的代码,现在得到以下错误:
org.springframework.beans.factory.NoSuchBeanDefinitionException: 没有符合条件的 bean 类型...
我的源代码位于src/main/java并且测试位于src/test/java但这并没有起到太大的作用,我将测试类移动到 main/java 并没有帮助。
@Component
public class MyClass {
@Autowired
MyService myService;
public void myMethod(Dog dog, Animal animal) {
if (myService.isAnimal(dog.getStatus()) {//NPE was on this line
dog.setName("mike");
} else {
dog.setName(null);
}
}
}
下面是测试代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyClass.class)
public class MyClassTest {
@Autowired
MyClass testObjMyClass;
@Test
public void testMyMethod() {
MyService myService = mock(MyService.class);
Dog dog = new Dog();
dog.setStatus("Y"); // this should give true for isAnimal()
when(myService.isAnimal(dog.getStatus())).thenReturn(true); // I tried with ("Y") as well
testObjMyClass.myMethod(dog, animal);// I defined animal in test Class variables before.
assertEquals("mike", dog.getName());
}
}
我的项目是 springboot 应用程序,myService 是在 myMethod() 中自动装配的。我会很感激你的建议!
解决方案
如果您有 spring boot 1.4 或更高版本,请尝试将 test 中的注释替换为:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)
这是由 Spring 团队创建的简化
如果您的 Spring boot 低于 1.4(即 1.3),则必须将加载程序添加到您的ContextConfiguration
:
@ContextConfiguration(classes=MyClass.class, loader=SpringApplicationContextLoader.class)
推荐阅读
- typescript - 尝试 setState 时出错 - 正在工作。最近更新坏了
- .net - Visual Studio 2019 MVC 项目模板无法编译
- spring-boot - 保护桌面应用程序客户端的 SpringBoot API
- html - 仅使用 CSS 的字体轮廓
- azure-devops - 我点击了权限 api,我想破译描述符 id
- sql - 如何从 MS Access 中的先前记录中停止 TOP 查找错误?
- ethereum - Solidity:如何在 compile.js 文件中编译多个智能合约?
- random - 希望在单元格中显示随机百分比
- excel-formula - 如何创建一个公式,该公式将在 A 列中具有相同值的多行创建边框
- java - 为什么输出不同,java继承?