首页 > 解决方案 > 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() 中自动装配的。我会很感激你的建议!

标签: javaspringspring-bootjunitmocking

解决方案


如果您有 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)

推荐阅读