1

Spring MVCアプリケーションがあり、ユニットテストにmockitoを使用しています。ユニットテストを実行すると、nullポインター例外が発生し続けます。:(

私の単体テストの基礎となる方法を以下に示します。

@Controller
public class LogInController {

    @Autowired
    private MessageSource messageSource;

    @RequestMapping(method = RequestMethod.POST, value = "/login")
    public ModelAndView validateViewLogin(@ModelAttribute Person person,
    BindingResult result, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        String userName = person.getFirstName();
        String password = person.getPassword();
        boolean isUserValid = false;
        if (userName != null && password != null) {
             isUserValid = userManagerService.validateUserLogin(userName,password);
        }
        if (!isUserValid) {
            mav.addObject("failLog",messageSource.getMessage("login.user.fail", new String[] {"  ", "" }, request.getLocale()));
            mav.addObject("isUserValid", false);
            mav.setViewName("login");
            return mav;
        }
        mav.addObject("isUserValid", isUserValid);
        mav.setViewName("home");
        return mav;
    }

私のユニットテストの下を見つけてください:

@Test
public void validateViewLogin_NotValidLogin_returnsLoginPage() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    Person person = new Person();
    person.setFirstName("John");
    person.setPassword("123");
    isUserValid = false;
    LogInController controller = new LogInController();

    // Inject mock user service into controller
    UserManagerService mockUserService =   mock(UserManagerService.class);
    controller.setUserManagerService(mockUserService);

    // Configure mock user service to accept the person
    when(mockUserService.validateUserLogin("John", "123")).thenReturn(
            isUserValid);

    // Attempt the validation
    ModelAndView mav = controller
            .validateViewLogin(person, result, request);

    // Check the result
    assertEquals("login", mav.getViewName());
}

上記の単体テストを実行すると、以下のスタックトレースエラーメッセージが表示されます。

java.lang.NullPointerException
at com.gemstone.presentation.LogInController.validateViewLogin(LogInController.java:99)
at com.gemstone.presentation.LogInControllerTest.validateViewLogin_NotValidLogin_returnsLoginPage(LogInControllerTest.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

基本的に、以下に示す行99は、スタックトレースに従ってnullを返します。

mav.addObject(
                "failLog",
                messageSource.getMessage("login.user.fail", new String[] {
                        "  ", "" }, request.getLocale()));

この行にnullポインタが表示される理由はありますか?ただし、アプリケーションを実行すると正常に動作し、ページにfailLogメッセージが表示されます。

前もって感謝します。

4

1 に答える 1

3

私の推測では、messageSourceはnullです。あなたはあなたのリクエストを嘲笑していますが、あなたのmessageSourceは嘲笑しておらず、あなたがログインコントローラを新しくしているところでは、それはSpringによって注入されていません。

実行中は、Springによって自動的に注入されます。

明確にするために編集:

まず、テストのために何らかの方法で設定できる必要があります。セッターまたはコンストラクターを追加して、次のように取得できます。

@Controller
public class LogInController {

    @Autowired
    private MessageSource messageSource;

    public void setMessageSource(MessageSource ms){
        this.messageSource = ms;
    }
    // ......
}

次に、テストも変更する必要があります。

    @Test
public void validateViewLogin_NotValidLogin_returnsLoginPage() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    Person person = new Person();
    person.setFirstName("John");
    person.setPassword("123");
    isUserValid = false;
    LogInController controller = new LogInController();

    // Inject mock user service into controller
    UserManagerService mockUserService =   mock(UserManagerService.class);

            /** ADDED **/
            MessageSource ms = mock(MessageSource.class);

    controller.setUserManagerService(mockUserService);
            /** ADDED **/
            controller.setMessageSource(ms);

    // Configure mock user service to accept the person
    when(mockUserService.validateUserLogin("John", "123")).thenReturn(
            isUserValid);

            /** ADDED **/
            when(ms.getMessage("login.user.fail", new String[] {"  ", "" }).thenReturn("message");

    // Attempt the validation
    ModelAndView mav = controller
            .validateViewLogin(person, result, request);

    // Check the result
    assertEquals("login", mav.getViewName());
}

これをフリーハンドで渡すだけなので、タイプミスがないことを確認してください。基本的に、UserManagerServiceと同じようにMessageSourceを試してみます。これは結局のところ単なるインターフェイスであり、まったく同じ方法でモックすることができます。

于 2013-01-23T18:44:03.833 に答える