【问题标题】:Test void methods with Autowired classes使用 Autowired 类测试 void 方法
【发布时间】:2019-06-24 12:15:04
【问题描述】:

我是Spring的初学者,如果它调用方法,我需要为这个类编写测试:

class ClassOne {

    @Autowired
    AutowiredClass a1;

    @Autowired
    AutowiredClass a2;

    void methodOne() {
        a1.method1();    
    }

    void methodTwo() {
        a2.method2();
    }
}

我试过写测试,但失败了,得到了 NPE:

class ClassOneTest {

    @Autowired
    ClassOneInterface c1i;

    @Test
    public void testMethod1() {
        c1i.methodOne();  // <- NPE appears here..
        Mockito.verify(ClassOne.class, Mockito.times(1));
    }
}

成功测试 void 方法会很棒。

【问题讨论】:

    标签: java spring testing


    【解决方案1】:

    您可以使用 unit 测试来验证:

    @RunWith(MockitoJUnitRunner.class)
    public class MyLauncherTest {
    
        @InjectMocks
        private ClassOne c1 = new ClassOne();
    
        @Mock
        private AutowiredClass a1;
    
        @Mock
        private AutowiredClass a2;
    
        @Test
        public void methodOne() {
            c1.methodOne(); // call the not mocked method
            Mockito.verify(a1).method1(); //verify if the a1.method() is called inside the methodOne
        }
    }
    

    【讨论】:

      【解决方案2】:

      ClassOne 定义了一个spring bean。为了自动装配 bean 的字段,您需要一个 Spring 上下文。

      如果您想将 ClassOne 作为 SPRING BEAN 进行测试,那么您需要使用 SpringTest。

      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration({MyConfig.class}) // Spring context config class
      class ClassOneTest {
      
          @Autowired
          ClassOneInterface c1i;
      ...
      }
      

      一个 ClassOne bean 将被注入到测试套件 c1i 字段中。

      然后你就可以使用 mockito 来监视现场了:

      ClassOne cSpy = spy(c1i);
      

      然后你就可以验证方法调用了:

      verify(cSpy).someMethod(someParam);
      

      希望对你有帮助

      【讨论】:

        【解决方案3】:

        您正在获得 NPE,因为您的测试用例中加载的上下文找不到您提到的自动装配 bean。您应该像这样注释测试类:

        @RunWith(SpringRunner.class)
        @SpringBootTest
        class ClassOneTest {
        
            @Autowired
            ClassOneInterface c1i;
        
            @Test
            public void testMethod1() {
                c1i.methodOne();  // <- NPE appears here..
                Mockito.verify(ClassOne.class, Mockito.times(1));
            }
        }
        

        考虑看看:Similar NPE test error

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-08-27
          • 1970-01-01
          • 2012-07-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多