服务单元测试SpringFramework

时间:2015-12-15 13:23:29

标签: java unit-testing

这些是我试图测试的服务和存储库类。

 @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)

StackTrace with @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)

1 个答案:

答案 0 :(得分:1)

使用Spring初始化自己的上下文后,您不必输入put @Mock注释。只需放@Autowired就可以了。

@Autowired
private BookRepository bookRepository;

在您提出@Autowired后,我建议您使用fest.assertions类,例如:

Assertions.assertThat( myBook ).isNotNull();

导入是:

import org.fest.assertions.Assertions;

编辑:由于您使用java.lang断言,因此您将始终获得例外。

  

AssertionError的含义是发生了一些事情   开发人员认为不可能发生。

     

因此,如果抛出AssertionError,它就是一个明显的标志   编程错误。

因此,如果您使用maven,则必须期待http://mvnrepository.com/artifact/org.easytesting/fest-assert,否则请将其下载为jar并将其添加到依赖项中。然后你可以使用我的建议。