2015-12-15 211 views
0

這些是我正在測試的服務和存儲庫類。服務單元測試SpringFramework

@Service 
public class BookServiceImpl implements BookService { 

    @Autowired 
    private BookRepository bookRepository; 

    @Override 
    public List<Book> getAllBooks() { 
     return bookRepository.getAllBooks(); 
    } 

    @Override 
    public Book getBookById(int productID) { 
     return bookRepository.getBookById(productID); 
    } 

    @Override 
    public List<Book> getBookByCategory(String category) { 
     return bookRepository.getBookByCategory(category); 
    } 

    @Override 
    public Set<Book> getBooksByFilter(Map<String, List<String>> filterParams) { 
     return bookRepository.getBooksByFilter(filterParams); 
    } 

} 

@Repository 
@Configuration 
public class InMemoryBookRepository implements BookRepository { 

    private List<Book> listOfProducts = new ArrayList<Book>(); 

    public InMemoryBookRepository() { 
     Book algorithms = new Book(1, "Book", "Book", 29); 
     algorithms.setDescription("description."); 
     algorithms.setCondition("Available"); 
     algorithms.setUnitsInStock(4); 
     algorithms.setCategory("java"); 
     algorithms.setManufacturer("Nenov"); 
     listOfProducts.add(algorithms); 
     Book book2 = new Book(2, "Thinking in Java", "Bruce Ekel", 5352); 
     book2.setDescription("Description"); 
     book2.setCondition("Available"); 
     book2.setUnitsInStock(100); 
     book2.setCategory("programming"); 
     book2.setManufacturer("Nikola"); 
     listOfProducts.add(book2); 
    } 

    @Override 
    public List<Book> getAllBooks() { 
     return listOfProducts; 
    } 

    @Override 
    public Book getBookById(int bookId) { 
     Book bookById = null; 
     for (Book book : listOfProducts) { 
      if (book != null && book.getId() != 0) { 
       bookById = book; 
       break; 
      } 
     } 
     return bookById; 
    } 

    @Override 
    public List<Book> getBookByCategory(String category) { 
     List<Book> productsByCategory = new ArrayList<Book>(); 
     for (Book book : listOfProducts) { 
      if (category.equalsIgnoreCase(book.getCategory())) { 
       productsByCategory.add(book); 
      } 
     } 
     return productsByCategory; 
    } 

    @Override 
    public Set<Book> getBooksByFilter(Map<String, List<String>> filterParams) { 
     Set<Book> productsByBrand = new HashSet<Book>(); 
     Set<Book> productsByCategory = new HashSet<Book>(); 
     Set<String> criterias = filterParams.keySet(); 
     if (criterias.contains("brand")) { 
      for (String brandName : filterParams.get("brand")) { 
       for (Book book : listOfProducts) { 
        if (brandName.equalsIgnoreCase(book.getManufacturer())) { 
         productsByBrand.add(book); 
        } 
       } 
      } 
     } 
     if (criterias.contains("category")) { 
      for (String category : filterParams.get("category")) { 
       productsByCategory.addAll(this.getBookByCategory(category)); 
      } 
     } 
     productsByCategory.retainAll(productsByBrand); 
     return productsByCategory; 
    } 

} 

我想在服務上進行單元測試,但有空指針異常。我希望有人會幫助。如果您需要更多代碼,請通知我。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration({ "Context.xml" }) 
public class BookServiceTest { 

    @Mock 
    private BookRepository bookRepository; 

    @Test 
    public void testGetBookById() { 
     Book book = new Book(1, "Book", "Book", 29); 

     int id = book.getId(); 

     assertNotNull("Object can not have null id ", id); 

     Book searchedBook = bookRepository.getBookById(id); // nullpointer here ! 
     assertNotNull("Book should be found ", searchedBook); 
     assertTrue("Found book id should be equal to id being searched", searchedBook.getId() == 1); 
    } 
} 

的context.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 

    <bean id="bookRepository" name="bookRepository" class="org.mockito.Mockito" 
     factory-method="mock"> 
     <constructor-arg value="com.book.contracts.BookRepository" /> 
    </bean> 
</beans> 

堆棧跟蹤:

java.lang.NullPointerException 
    at store.BookServiceTest.testGetBookById(BookServiceTest.java:30) 
    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:50) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73) 
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) 
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73) 
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) 
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 

堆棧跟蹤與@Autowired

java.lang.AssertionError: Book should be found 
    at org.junit.Assert.fail(Assert.java:88) 
    at org.junit.Assert.assertTrue(Assert.java:41) 
    at org.junit.Assert.assertNotNull(Assert.java:712) 
    at store.BookServiceTest.testGetBookById(BookServiceTest.java:32) 
    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:50) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73) 
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) 
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73) 
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) 
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 

編輯:

@Test 
    public void testGetBookById() { 
     Book book = new Book(1, "Book", "Book", 29); 

     int id = book.getId(); 
     assertNotNull("Object can not have null id ", id); 

     Book searchedBook = bookRepository.getBookById(id); 
     Assertions.assertThat(searchedBook).isNotNull(); 
     assertTrue("Found book id should be equal to id being searched", searchedBook.getId() == 1); 
    } 

堆棧跟蹤

java.lang.AssertionError: expecting actual value not to be null 
    at org.fest.assertions.Fail.failure(Fail.java:228) 
    at org.fest.assertions.Fail.fail(Fail.java:167) 
    at org.fest.assertions.Fail.failIfActualIsNull(Fail.java:100) 
    at org.fest.assertions.GenericAssert.isNotNull(GenericAssert.java:238) 
    at store.BookServiceTest.testGetBookById(BookServiceTest.java:31) 
    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:50) 
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) 
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73) 
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) 
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73) 
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83) 
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) 
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) 
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) 
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) 
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) 
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68) 
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163) 
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) 
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) 
+0

你可以添加stacktrace嗎? – IlGala

+0

@IlGala堆棧跟蹤添加。 – NoSuchUserException

+0

您是否在此存儲庫變量上嘗試'@InjectMocks'和'@Autowired'? –

回答

1

後,您使用Spring初始化自己的環境下,你不必鍵入放@Mock註解。只要把@Autowired,你很好去。

@Autowired 
private BookRepository bookRepository; 

你把@Autowired後,我建議你使用fest.assertions類如:

Assertions.assertThat(myBook).isNotNull(); 

,進口是:

import org.fest.assertions.Assertions; 

編輯:由於您使用java.lang斷言,你總會得到例外。

AssertionError的含義是發生了什麼事情, 開發人員認爲是不可能發生的。

所以如果一個AssertionError被拋出,這是一個清晰的跡象 編程錯誤。

所以你必須期待http://mvnrepository.com/artifact/org.easytesting/fest-assert,如果你正在使用maven,否則將它下載爲jar並將其添加到你的依賴關係。然後你可以使用我的建議。

+0

我必須把這個 - Assertions.assertThat(myBook).isNotNull(); – NoSuchUserException

+0

這只是一個建議,而不是使用assertNotNull(「Book should be found」,searchBook);你不應該得到一個斷言情況的例外。 –

+0

我無法導入,但...這並不重要。你知道如何解決Autowired字段的問題嗎? – NoSuchUserException