Junit如何在测试方法中模拟方法返回?

时间:2019-05-24 09:14:40

标签: java spring spring-boot junit mocking

我通过以下方法的测试得到了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()中自动装配。我会感谢您的提示!

2 个答案:

答案 0 :(得分:1)

如果您具有Spring Boot 1.4或更高版本,请尝试使用以下命令替换测试中的注释:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment=WebEnvironment.NONE)

这是Spring团队创建的简化

如果您的Spring引导低于1.4(即1.3),则必须将加载程序添加到ContextConfiguration中:

@ContextConfiguration(classes=MyClass.class, loader=SpringApplicationContextLoader.class)

答案 1 :(得分:1)

您正在模拟类MyService,但没有将其注入MyClass中。 如果您使用的是模仿,请尝试

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

            @Mock
            MyService myService;

            @InjectMocks
            MyClass testObjMyClass;

            @Before
            public void setup() {
                MockitoAnnotations.initMocks(this);
                when(myService.isAnimal(dog.getStatus())).thenReturn(true);
            }

            @Test
            public void testMyMethod() {

                Dog dog = new Dog();
                dog.setStatus("Y"); // this should give true for isAnimal()

                testObjMyClass.myMethod(dog, animal);// I defined animal in test Class variables before.
                assertEquals("mike", dog.getName());
            }

        }
相关问题