0
public  class PersistenceManager {

    public boolean addUser(User user) {
        UserPersistor userPersistor = new UserPersistor(user) {

            @Override
            void somemethod() {
                // TODO Auto-generated method stub
                
            }
            
        };
        userPersistor.addUser();
        System.out.println("PersistenceManager added user ");
        return true;
    }
    
    
    class User {
        
        public String firstName;
        public String lastName;
        
        
        public User(String firstName, String lastName) {
            super();
            this.firstName = firstName;
            this.lastName = lastName;
        }       
    }
    
    abstract class UserPersistor {
        
        public UserPersistor( ) {
            
        }
        public UserPersistor(User user) {
            
        }
        public void addUser() {
            System.err.println("UserPersistor added user ");
        }
        abstract void somemethod();
    }
}   

import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.expectNew;
import static org.powermock.api.easymock.PowerMock.expectLastCall;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest( PersistenceManager.class )
public class PersistenceManagerTest {
    
    private User user = null;
    
    @Before
    public void before() throws Exception {
        
        user = createMock(User.class);      
        UserPersistor userPersistor = createMock(UserPersistor.class);
        userPersistor.addUser();
        expectLastCall();
        
        expectNew(UserPersistor.class, user).andReturn(userPersistor);      

        PowerMock.replayAll();
    }
    @Test
    public void testaddUser() {

        PersistenceManager tested = new PersistenceManager();
        tested.addUser(user);
        PowerMock.verifyAll();
    }
}

上面的代码有什么问题?我没有看到 UserPersistor 的模拟对象。意思是,我不想看到“UserPersistor added user”打印出来。它不应该做任何事情。但它正在打印它,因为创建了 UserPersistor 的真实对象。我在我的实际项目中遇到了这个问题,我认为会模拟并尝试在更小的环境中解决。但我很难过。

4

1 回答 1

0

那是因为您不希望实例化UserPersistor,而是希望实例化一个匿名内部类扩展UserPersistor.

为此,您需要检索该类,模拟它并期待它。PowerMock 有一个Whitebox类可以做到这一点。您在使用它时公开了类实现。我建议您重构代码以注入代码。但如果你真的想,你应该这样写:

@Before
public void before() throws Exception {
    user = createMock(PersistenceManager.User.class);

    Class<Object> clazz = Whitebox.getAnonymousInnerClassType(PersistenceManager.class, 1);
    PersistenceManager.UserPersistor userPersistor = createMock(clazz);
    userPersistor.addUser();

    expectNew(clazz, user).andReturn(userPersistor);

    PowerMock.replayAll();
}
于 2021-08-22T01:50:39.497 回答