alibaba / testable-mock

换种思路写Mock,让单元测试更简单
https://alibaba.github.io/testable-mock/
MIT License
1.83k stars 310 forks source link

无法通过约定定位到Mock类 #195

Closed imzhizi closed 2 years ago

imzhizi commented 3 years ago

必须在 ControlServiceImplTest 中增加注解 @MockWith(FileManagerMock.class) 方可运行

└── company
    └── group
        └── service
            └── worka
                └── task
                    ├── meat
                    │   └── processor
                    │       └── FileManagerMock.java
                    ├── service
                        └── impl
                            └── ControlServiceImplTest.java
@EnablePrivateAccess
// @MockWith(FileManagerMock.class) 不加会报NPE
public class ControlServiceImplTest {

    private ControlServiceImpl controlService = new ControlServiceImpl();

    public ControlServiceImplTest() {
        controlService.fileManager = new FileManager();
    }

    @Test
    public void test() {
        assertTrue(controlService.isNewCondition(444L));
    }

}

---

    public boolean isNewCondition(long poiId) {
        Set<Long> whitePoiSet = fileManager.getPoiIds();
        return whitePoiSet.contains(poiId);
    }

---

public class FileManagerMock {
    @MockMethod(targetClass = FileManager.class, scope = MockScope.GLOBAL)
    public Set<Long> getPoiIds() {
        return Sets.newHashSet(111L, 222L, 333L);
    }
}
----

public class FileManager implements IFileParser {
     public Set<Long> getPoiIds() {
        return poiIds;
    }
}
linfan commented 3 years ago

对于ControlServiceImplTest测试类,自动关联的Mock容器类是ControlServiceImplTest.MockControlServiceImplMock。如果要使用FileManagerMock作为Mock容器类,确实需要使用@MockWith注解。