2016-12-19 6 views
3

私のSpring ControllerでメソッドのJUnitテストを作成しようとしていますが、テストが正しく行われないようです。私がテストしているときに、コントローラのDB接続をautowireしているようではありません。Springデータautowired db接続がJUnitテストでは機能しません

コントローラ

@Controller 
public class PollController { 

    @Autowired 
    private PollRepository pollrepo; 

    @RequestMapping(value = "/{id}", method = RequestMethod.GET) 
    public String getPoll(@PathVariable String id, Model model) { 
     try { 
      Poll poll = pollrepo.findById(id); 
      if(poll == null) throw new Exception("Poll not found"); 
      model.addAttribute("poll", poll); 
      return "vote"; 
     } catch (Exception e) { 
      return "redirect:/errorpage"; 
     } 
    } 
} 

とJUnitテストクラス

public class PollControllerTest { 

    public PollControllerTest() { 
    } 

    @BeforeClass 
    public static void setUpClass() { 
    } 

    @AfterClass 
    public static void tearDownClass() { 
    } 

    @Before 
    public void setUp() { 
    } 

    @After 
    public void tearDown() { 
    } 


    @Test 
    public void testGetPoll() { 
     System.out.println("getPoll"); 
     String id = "5856ca5f4d0e2e1d10ba52c6"; 
     Model model = new BindingAwareModelMap(); 
     PollController instance = new PollController(); 
     String expResult = "vote"; 
     String result = instance.getPoll(id, model); 
     assertEquals(expResult, result); 
    } 
} 

私はここで何かが足りないのですか?

答えて

1

それはなりませんautowireデータベース接続、あなたのjunitcontrollerインスタンスは、春のコンテナによって管理されていないため。

キーワードnewを使用してPollControllerのインスタンスを作成しました。したがって、これは春管理Beanではありません。

PollController instance = new PollController(); 

私はこれをやってみたとき、それは私に次のエラーを与える

@RunWith(SpringJUnit4ClassRunner.class) 
class PollControllerTest { 

    //Object under test 
    @Autowired 
    PollController instance; 
+0

@RunWith(SpringJUnit4ClassRunner.class)であなたのテストクラスに注釈を付けると、テストのためのコントローラを注入することをお勧めします:org.springframework.beans.factory.UnsatisfiedDependencyExceptionを: 'poll.PollControllerTest'という名前のBeanを作成中にエラーが発生しました:フィールド 'instance'で表現されている満足度の低い依存関係。ネストされた例外はorg.springframework.beans.factory.NoSuchBeanDefinitionExceptionです: 'poll.PollController'タイプの適格なBeanはありません:autowire候補と見なされる少なくとも1つのbeanが必要です。依存関係の注釈:{@ org.springframework.beans.factory.annotation.Autowired(必須= true)} – MattH

+0

設定XMLファイルを追加します。私はあなたが注釈の設定とコンポーネントのスキャンの設定を使用していないと思う。 – ScanQR

+0

私はそれがないようです、それは問題かもしれません? – MattH

0

はい。 pollrepoは外部依存関係なので、テストクラスでそれを擬似する必要があります。以下のコードを参照してください。

class PollControllerTest { 

    //Object under test 
    PollController instance; 

    @Mock 
    private PollRepository pollrepo; 

    @Before 
    public void setUp() { 

     instance = new PollController(); 

     ReflectionTestUtils.setField(instance, "pollrepo", pollrepo); 
    } 

    //Tests goes here 
} 
関連する問題